﻿/****************************************************************************
*                                                                           *
* Copyright (c) RSC. All rights reserved(2010).								*
* Developers: Marius Ionescu, Cristian Bojinovici     						*
*                                                                           *
****************************************************************************/

using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.Web.Security;
using System.Web.UI.WebControls;
using NS_Controls;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.UI;
using AjaxControlToolkit;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.IO;
using ExportTools;
using XMLTools;
using System.Configuration;

public partial class ExportSIUI : SessionPageBase, ICallbackEventHandler
{
    protected string SortField = "";
    string validationXSDFile = string.Empty;
    string sqlError = string.Empty;
	/// <summary>
	/// #DEFINE Value for the position of the first element of lists = 1.
	/// </summary>
	private static readonly int CounterStart = 1;

	#region history grid management
	#region sorting details
	private string GridViewSortDirection
    {
        get { return (string)(this.ViewState["GridViewSortDirection"] != null ? this.ViewState["GridViewSortDirection"] : "DESC"); }
        set { this.ViewState["GridViewSortDirection"] = value; }
    }

	private string ToggleSortDirection()
    {
        switch (GridViewSortDirection)
        {
            case "ASC":
                GridViewSortDirection = "DESC";
                break;
            case "DESC":
                GridViewSortDirection = "ASC";
                break;
        }
        return GridViewSortDirection;
	}
	#endregion

	ICollection CreateDataSource()
    {
        try
        {
            DataSet ds = Hipocrate.DB.DBConnection.GetData("EXP_SIUI_EXPORT", new string[] { "UserHipo" }, new object[] { !string.IsNullOrEmpty(Tools.userHipoSession) ? Tools.userHipoSession : "UnknownUser" });
            DataView dv = ds.Tables[0].DefaultView;
            if (SortField != "")
                dv.Sort = SortField + " " + ToggleSortDirection();
            return dv;
        }
        catch (Exception ex)
        {
			this.Master.SetMessage("Error creating DataSource: " + ex.Message, true);
			return null;
        }
    }

    protected void MyDataGrid_Page(object sender, DataGridPageChangedEventArgs e)
    {
        HistoryGrid.CurrentPageIndex = e.NewPageIndex;
        BindGrid();
    }

    protected void MyDataGrid_Sort(Object sender, DataGridSortCommandEventArgs e)
    {
        SortField = e.SortExpression;
        BindGrid();
    }

    protected void BindGrid()
    {
        try
        {
			HistoryGrid.DataSource = CreateDataSource();
			HistoryGrid.DataBind();
        }

        catch (Exception ex)
        {
            this.Master.SetMessage("Error binding data: " + ex.Message, true);
        }
	}

	#region allow user to change page size
	TextBox txtPageSize = null;
	protected void HistoryGrid_ItemCreated(object sender, DataGridItemEventArgs e)
	{
		if (e.Item.ItemType == ListItemType.Pager)
		{
			TableCell cellPageSize = new TableCell();
			cellPageSize.HorizontalAlign = HorizontalAlign.Center;
			cellPageSize.ColumnSpan = 3;
			e.Item.Cells.AddAt(0, cellPageSize);
			cellPageSize.Controls.Add(new Literal() { Text="Page Size:&nbsp;" });
			txtPageSize = new TextBox();
			txtPageSize.AutoPostBack = true;
			txtPageSize.ID = "txtPageSize";
			txtPageSize.Style.Add(HtmlTextWriterStyle.TextAlign, "right");
			txtPageSize.Style.Add(HtmlTextWriterStyle.Width, "42px");
			txtPageSize.TextChanged += new EventHandler(txtPageSize_TextChanged);
			//also tag it with a default value to be displayed:
			txtPageSize.Attributes.Add("current", HistoryGrid.PageSize.ToString());
			cellPageSize.Controls.Add(txtPageSize);
			FilteredTextBoxExtender validatorPageSize = new FilteredTextBoxExtender();
			validatorPageSize.TargetControlID = txtPageSize.ID;
			validatorPageSize.ValidChars = "0123456789";
			cellPageSize.Controls.Add(validatorPageSize);
			//cellPageSize.Controls.Add(new Literal() { Text = "&nbsp;" });
			//cellPageSize.Controls.Add(new Button() { Text = "Set" });

			this.PreRender += new EventHandler(ExportSIUI_PreRender);
		}
	}

	void ExportSIUI_PreRender(object sender, EventArgs e)
	{
		if (txtPageSize.Text.Length == 0)
			txtPageSize.Text = txtPageSize.Attributes["current"];
		txtPageSize.Attributes.Remove("current");
	}

	protected void txtPageSize_TextChanged(object sender, EventArgs e)
	{
		TextBox txtPageSize = sender as TextBox;
		int nPageSize = int.Parse(txtPageSize.Text);
		if (nPageSize < 5) nPageSize = 5;
		if (nPageSize > 100) nPageSize = 100;
		txtPageSize.Text = (HistoryGrid.PageSize = nPageSize).ToString();
		BindGrid();
	}
	#endregion
	#endregion

	protected void Page_Load(object sender, EventArgs e)
    {
        Load_Data(false);

        if (!IsPostBack)
        {
            ClearSession("ds_Types");
            ClearSession("ds_Items");

			//TODO: DateFormat = GetCurrentDateFormat(user.LanguageSetting);
			txtStart_Date.Text = DateTime.Now.Date.ToString(DateFormat);
			txtEnd_Date.Text = DateTime.Now.Date.ToString(DateFormat);
			calDataStart.Format = calDataEnd.Format = calDataStartOnFocus.Format = calDataEndOnFocus.Format = DateFormat;

            drpPeriod.Enabled = false;
            drpInsurer.Enabled = false;
        }

		HistoryGrid.SelectedIndex = -1;
    }

    private void Load_Data(bool bForce)
    {
        try
        {
            DataSet ds_Types = Hipocrate.DB.DBConnection.GetData("EXPORT_TYPE_Select", new string[] { }, new object[] { });
            DataView dv0 = ds_Types.Tables[0].DefaultView;

            if (!IsPostBack)
            {
                drpTypes.DataSource = dv0;
                drpTypes.DataTextField = "Name";
                drpTypes.DataValueField = "ID";
                drpTypes.DataBind();

				#region if no "Salarizare" around, hide that row
				trSalarizare.Visible = false;
				for (int i = 0; i < dv0.Count; ++i)
				{
					string code = dv0[i]["Code"].ToString().Trim();
					drpTypes.Items[i].Attributes.Add("tag", code);
					if (code.Equals("SAL"))
						trSalarizare.Visible = true;
				}
				#endregion

				TypeCodes = ds_Types.Tables[0];

                BindGrid();
            }

            DataSet ds_Items = Hipocrate.DB.DBConnection.GetData("EXPORT_TYPE_ITEMS_Select", new string[] { "TypeID" }, new object[] { drpTypes.SelectedValue });
            DataView dv1 = ds_Items.Tables[0].DefaultView;

            if (!IsPostBack)
            {
                drpItems.DataSource = dv1;
                drpItems.DataTextField = "Name";
                drpItems.DataValueField = "ID";
                drpItems.DataBind();
				drpItems.Enabled = (drpItems.Items.Count > 1);

				for (int i = 0; i < dv1.Count; ++i)
					drpItems.Items[i].Attributes.Add("tag", dv1[i]["Code"].ToString().Trim());
				ItemCodes = ds_Items.Tables[0];
			}

            SetSession("ds_Types", ds_Types);
            SetSession("ds_Items", ds_Items);
        }

        catch (Exception ex)
        {
			this.SetMessage("Cannot Load ExportData: " + ex.Message, true);
        }
    }

    protected void On_SelectedIndexChanged(object sender, EventArgs e)
    {
		try
        {
			DataView dv = new DataView((GetSessionDataSet("ds_Items")).Tables[0]);

			drpItems.DataSource = dv;
			drpItems.DataTextField = "Name";
			drpItems.DataValueField = "ID";
			drpItems.DataBind();
			drpItems.Enabled = (drpItems.Items.Count > 1);
			ItemCodes = GetSessionDataSet("ds_Items").Tables[0];

            DataSet ds_PeriodInsurer = null;

            if (drpTypes.SelectedItem.Text == "Salarizare")
            {
				drpPeriod.Enabled = true;
				drpInsurer.Enabled = true;
				try
                {
                    ds_PeriodInsurer = Hipocrate.DB.DBConnection.GetData("PERIODS_INSURERS_Select", new string[] { }, new object[] { });
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
					this.SetMessage("Error reading PERIODS_INSURERS.", true);
					output.Text = "I" + Tools.HiddenExceptionDetails(ex);
                    return;
                }
				DataView dvP = ds_PeriodInsurer.Tables[0].DefaultView;
				DataView dvI = ds_PeriodInsurer.Tables[1].DefaultView;

                drpPeriod.DataSource = dvP;
                drpPeriod.DataTextField = "MonthCode";
                drpPeriod.DataValueField = "ID";
                drpPeriod.DataBind();

                drpInsurer.DataSource = dvI;
                drpInsurer.DataTextField = "ID";
                drpInsurer.DataValueField = "ID";
                drpInsurer.DataBind();

            }
            else
            {
                drpPeriod.Enabled = false;
                drpInsurer.Enabled = false;
                drpPeriod.Items.Clear();
                drpInsurer.Items.Clear();
            }
        }

        catch (Exception ex)
        {
            this.Master.SetMessage("Cannot update related fields: " + ex.Message, true);
        }
    }

	private object TypeCodes
	{
		get { return this.ViewState["typeCodes"] as Hashtable; }
		set
		{
			DataTable source = value as DataTable;
			if (source == null) return;
			Hashtable result = new Hashtable(source.Rows.Count);
			foreach (DataRow row in source.Rows)
				result[row["ID"].ToString()] = row["Code"];
			this.ViewState["typeCodes"] = result;
		}
	}
	private object ItemCodes
	{
		get { return this.ViewState["itemCodes"] as Hashtable; }
		set
		{
			DataTable source = value as DataTable;
			if (source == null) return;
			Hashtable result = new Hashtable(source.Rows.Count);
			foreach (DataRow row in source.Rows)
				result[row["ID"].ToString()] = row["Code"];
			this.ViewState["itemCodes"] = result;
		}
	}

    protected void btnExportSIUI_Click(object sender, EventArgs e)
    {
		try
		{
			if (string.IsNullOrEmpty(txtStart_Date.Text) || string.IsNullOrEmpty(txtEnd_Date.Text))
			{
				this.SetMessage("Nu ati selectat data start sau data sfarsit.", true);
				return;
			}

			string userHypo, typeC, itemC;

			if (!string.IsNullOrEmpty(Tools.userHipoSession))
				userHypo = Session["userHipoSession"].ToString();
			else
				userHypo = "UnknownUser";

            if ((TypeCodes as Hashtable) != null)
                typeC = (TypeCodes as Hashtable)[drpTypes.SelectedValue].ToString().Trim();
            else
                throw new ApplicationException("Cannot find dbCode for the selected Type");
            if ((ItemCodes as Hashtable) != null)
                itemC = (ItemCodes as Hashtable)[drpItems.SelectedValue].ToString().Trim();
            else
                throw new ApplicationException("Cannot find dbCode for the selected Item");

			ExportStatus status = ProcessExport(txtStart_Date.Text, txtEnd_Date.Text, drpTypes.SelectedValue, drpItems.SelectedValue, drpPeriod.SelectedValue, drpInsurer.SelectedValue, userHypo, typeC, itemC);

			BindGrid();
			if (status != ExportStatus.NotGenerated)
			{
				HistoryGrid.SelectedIndex = 0;
				HistoryGrid.SelectedItemStyle.BackColor =
					status == ExportStatus.GeneratedOk ? System.Drawing.Color.Yellow :
					status == ExportStatus.FailedButGenerated ? System.Drawing.Color.LightPink : System.Drawing.Color.Transparent;

				if (status == ExportStatus.GeneratedOk)
					this.Master.SetMessage("Exportul s-a realizat cu succes. Observatii: " +
						string.Join(" ", validationResult.ToArray()).RemoveHtml(), false);
			}
        }

		catch (Exception ex)
		{
			this.Master.SetMessage(ex.Message, true);
			output.Text = "!" + Tools.HiddenExceptionDetails(ex);
		}
		finally
		{
			string js = "hideModal()";
			ScriptManager.RegisterStartupScript(this, typeof(ExportSIUI), "hideModal", js, true);
		}
	}

	#region Object Orientation

	public enum ExportStatus { NotGenerated, FailedButGenerated, GeneratedOk };

	private abstract class ExportParameters
	{
		public string exportTypeId = null;
		public string exportItemId = null;
		public string userHipo = null;

		public ExportParameters(string type, string item, string userHipo)
		{
			this.exportTypeId = type;
			this.exportItemId = item;
			this.userHipo = userHipo;
		}

		#region "interface"
		public abstract string[] Names { get; }
		public abstract object[] Values { get; }
		#endregion

		public string GetXSDValidationFile()
		{
			string validationXSDFile = null;

			DataSet dsXSDPath = Hipocrate.DB.DBConnection.GetData("EXPORT_TYPE_ITEMS_Select", new string[] { "TypeID", "UserHipocrate" }, new object[] { exportTypeId, userHipo });

			if (dsXSDPath.Tables[0].TableName == "ErrorTable")
			{
				throw new Exception(dsXSDPath.Tables[0].Rows[0]["ErrorColumn"].ToString());
			}
			else
			{
				DataTable table = dsXSDPath.Tables[0];
				DataColumn primary = table.Columns["ID"];
				table.PrimaryKey = new DataColumn[] { primary };
				DataRow dr = table.Rows.Find(exportItemId);
				validationXSDFile = dr != null && (dr["XSD_PATH"].ToString() != string.Empty && dr["XSD_PATH"] != DBNull.Value)
					? System.Web.HttpContext.Current.Request.MapPath(dr["xsd_path"].ToString()) : "";
			}

			if (Path.GetFileName(validationXSDFile) == string.Empty)
				throw new ApplicationException("Nu este indicat numele fisierul xsd in tabelul EXPORT_ITEMS. Verificati.");

			if (validationXSDFile == "")
				throw new ApplicationException("Nu este indicata calea catre fisierul xsd in tabelul EXPORT_ITEMS. Verificati.");

			if (!File.Exists(validationXSDFile))
				throw new ApplicationException(string.Format("Validare imposibila. Nu exista fisierul de validare {0}", validationXSDFile));

			return validationXSDFile;
		}

		public string LocateTargetFolder()
		{
			string result = System.Web.HttpContext.Current.Request.MapPath("~/Tools/TempFiles/");
			result = result + userHipo;
			if (!Directory.Exists(result))
				Directory.CreateDirectory(result);
			return result;
		}
	}

	private class StandardExportParameters : ExportParameters
	{
		public string startDate = null;
		public string endDate = null;
		//public string Type { get { return exportTypeId; } }
		//public string Item { get { return exportItemId; } }

		public StandardExportParameters(string type, string item, string userHipo, string startDate, string endDate)
			: base(type, item, userHipo)
		{
			this.startDate = startDate;
			this.endDate = endDate;
		}

		public override string[] Names
		{
			get
			{
				return new string[] { "StartDate", "EndDate", "ExportID", "ItemID", "UserHipo" };
			}
		}

		public override object[] Values
		{
			get
			{
				return new object[] { StartDate, EndDate, exportTypeId, exportItemId, userHipo };
			}
		}

		public DateTime StartDate { get { return Tools.GetDateTime(startDate, DateFormat); } }
		public DateTime EndDate { get { return Tools.GetDateTime(endDate, DateFormat); } }

		public object[] ValuesWithoutTime
		{
			get
			{
				return new object[] { StartDate.Date, EndDate.Date, exportTypeId, exportItemId, userHipo };
			}
		}
	}

	private class SalarizareExportParameters : ExportParameters
	{
		public string period = null;
		public string insurer = null;
		public SalarizareExportParameters(string type, string item, string userHipo, string period, string insurer)
			: base(type, item, userHipo)
		{
			this.period = period;
			this.insurer = insurer;
		}

		public override string[] Names
		{
			get { return new string[] { "PeriodID", "INSURERID", "ExportID", "ItemID", "UserHipo" }; }
		}

		public override object[] Values
		{
			get { return new object[] { Convert.ToInt32(period), Convert.ToInt32(insurer), exportTypeId, exportItemId, userHipo }; }
		}
	}
	#endregion

	[WebMethod, ScriptMethod]
	private ExportStatus ProcessExport(string startDate, string endDate, string type, string item, string period, string insurer, string userHipo, string typeCode, string itemCode)
    {
		try
		{
			StandardExportParameters parametersStd = new StandardExportParameters(type, item, userHipo, startDate, endDate);
			SalarizareExportParameters parametersSal = new SalarizareExportParameters(type, item, userHipo, period, insurer);
			switch (typeCode)
			{
				case "CLIN"://CLINIC - da
					return DoExport("EXP_SIUI_CLINIC", parametersStd, null, DoExportSIUI_1);

				case "FARMCI"://FarmacieCI - da
					return DoExport("EXP_SIUI_FarmacieCI", parametersStd, null, DoExportSIUI_2);

				case "SP_DRG"://Spital_DRG - da
					return DoExport("EXP_SIUI_Spital_DRG", parametersStd, CounterValidator, DoExportSIUI_3);

				case "SP_SPZ"://Spz_AnalitycalReport - da
					return DoExport("EXP_SIUI_Spz_AnalitycalReport", parametersStd, null, DoExportSIUI_4);

				case "PARA"://Paraclinic -- inactive
					return DoExport("EXP_SIUI_Paraclinic", parametersStd, null, DoExportSIUI_5);

				case "DIA"://Hemodializa -- inactive
					return DoExport("EXP_SIUI_Dializa", parametersStd, null, DoExportSIUI_6);

				case "SP_DRG_CHR"://Spital_DRG_Cronici (aka Sp_DRG_CHRONICS) - da
					return DoExport("EXP_SIUI_Spital_DRG_Cronici", parametersStd, CounterValidator, DoExportSIUI_7);

				case "SP_DRG_ACU"://Spital_DRG_Acuti - da
					return DoExport("EXP_SIUI_Spital_DRG_Acuti", parametersStd, null, DoExportSIUI_8);

				case "DIA_HEMO"://DializaP_Hemodializa (aka EXP_SIUI_RRR_DializaPeritoneala_Hemodializa) -- inactive
					return DoExport("EXP_SIUI_RRR_DializaPeritoneala_Hemodializa", parametersStd, null, DoExportSIUI_9);

				case "PNS"://"Program National Sanatate" (aka EXP_SIUI_PNS) - da
					//NB: a switch might be needed? There are 5 subitems (all active!):
					//11	1.A - Subprogramul de tratament si monitorizare a persoanelor cu infectie HIV/SIDA si trat. postexpunere	"1.A"	~/Validation_XSD_Files/NHPREP_NhpReport.xsd
					//12	1.B - Subprogramul de tratament al bolnavilor de tuberculoza												"1.B"	~/Validation_XSD_Files/NHPREP_NhpReport.xsd
					//13	3 - Programul national de oncologie																			"3"		~/Validation_XSD_Files/NHPREP_NhpReport.xsd
					//14	5 - Programul national de diabet zaharat																	"5"		~/Validation_XSD_Files/NHPREP_NhpReport.xsd
					//15	6.1 - Hemofilie si talasemie
					return DoExport("EXP_SIUI_PNS", parametersStd, null, DoExportSIUI_10);

				case "PNSCj"://"Cereri justificative" (aka EXP_SIUI_PNS_NhpCJ) - da
					return DoExport("EXP_SIUI_PNS_NhpCJ", parametersStd, null, DoExportSIUI_11);

				case "AMB"://Ambulanta (aka EXP_SIUI_REC_AMB) -- inactive
					return DoExport("EXP_SIUI_REC_AMB", parametersStd, null, DoExportSIUI_12);

				case "13"://EXP_SIUI_REC_PREV
					return DoExport("EXP_SIUI_REC_PREV", parametersStd, null, DoExportSIUI_13);

				#region missing exports
				/*/NB: missing: (all inactive)
				12	EMP       	Angajatori
							17	@12	Angajatori	False	EMP	~/Validation_XSD_Files/
				13	SICK      	Concedii medicale
							18	@13	Concedii medicale	False	SICK	~/Validation_XSD_Files/
				14	MD        	Dispozitive medicale
							19	@14	Dispozitive medicale	False	MD	~/Validation_XSD_Files/MD_Report.xsd
				15	HC        	Ingrijiri domiciliu
							20	@15	Ingrijiri domiciliu	False	HC	~/Validation_XSD_Files/HC_Report.xsd
				16	MF        	Medicina familie
							21	@16	Medicina familie	False	MF	~/Validation_XSD_Files/MF_Report.xsd
				17	RECA      	Recuperare ambulatorie
							22	@17	Recuperare ambulatorie	False	RECA	~/Validation_XSD_Files/RECA_Report.xsd
				18	RECS      	Recuperare sanatorii
							23	@18	Recuperare sanatorii	False	RECS	~/Validation_XSD_Files/RECS_Report.xsd
				19	STOM      	Stomatologie
				24	@19	Stomatologie	False	STOM	~/Validation_XSD_Files/STOM_Report.xsd
				// */
				#endregion

				case "SAL"://Salarizare (aka EXP_SAL)
					switch (itemCode)
					{
						case "SAL_1C"://Sanatate 1C
							return DoExport("RPT_SANATATE_EXPORT_SANATATE_1C", parametersSal, null, DoExportSIUI_Sanatate_1C);
						case "SAL_2A"://Sanatate 2A
							return DoExport("RPT_SANATATE_EXPORT_SANATATE_2A", parametersSal, null, DoExportSIUI_Sanatate_2A);
						case "SAL_2B"://Sanatate 2B
							return DoExport("RPT_SANATATE_EXPORT_SANATATE_2B", parametersSal, null, DoExportSIUI_Sanatate_2B);
						//NB: not handled(!):
						case @"SAL_A1": // FNUASS A1 ; ~/Validation_XSD_Files/STOM_Report.xsd
							break;
						case @"SAL_A2": // FNUASS A2 ; ~/Validation_XSD_Files/STOM_Report.xsd
							break;
					}
					break;

				case "PRI"://Export Primarie (aka EXP_PRI)
					//new StandardExportParameters(type, item, userHipo, startDate, endDate);
					return DoExport("Prim_SpitalGet", parametersStd, null, DoExportSIUI_26);

				case "PALIATIV":
					return DoExport("EXP_SIUI_Paliativ", parametersStd, null, DoExportSIUI_Paliativ);

				default:
					this.SetMessage("Unknown Code: " + type.Trim(), true);
					break;
			}
			return ExportStatus.NotGenerated; //nothing to export...
        }
       catch (Exception ex)
       {
           this.SetMessage(ex.Message, true);
		   output.Text = "p" + Tools.HiddenExceptionDetails(ex);
		   return ExportStatus.NotGenerated;
       }
    }

	private static string DateFormat = "yyyy-MM-dd";
    private static object GetDate(string txtControl)
    {
        string value = txtControl.Trim();
        if (value.Length == 0)
            return null;
        DateTime result;
        if (DateTime.TryParse(value, out result))
            return result.ToShortDateString();
        return null;
    }

	delegate bool Validator(DataSet data, out List<string> details);
	delegate void Writer(DataSet data, ExportParameters p, System.Xml.XmlTextWriter objWriter);

	private int emptyAttributes = 0;

	List<string> validationResult = new List<string>();
	private ExportStatus DoExport(string procedureName, ExportParameters parameters, Validator delegatedValidator, Writer delegatedWriter)
	{
        try
        {
			DataSet data = Hipocrate.DB.DBConnection.GetData(procedureName, parameters.Names, parameters.Values);
			bool shouldValidateXsd = true;
			if (delegatedValidator != null)
			{
				shouldValidateXsd = delegatedValidator(data, out validationResult);
				if (!shouldValidateXsd) //current validation failed, no need for that other, expensive, one...
				{
					output.Text = "<b><u>Informatiile aduse din baza de date sunt inconsistente.</u></b> <br/>Detalii: ";
					string message = output.Text.RemoveHtml();
					int warningCount = 0, errorCount = 0;
					foreach (string line in validationResult)
					{
						output.Text += "<br/>";
						if (line.StartsWith("(")) //mere warning
						{
							++warningCount;
							output.Text += string.Format("<i>{0}</i>", line);
						}
						else
						{
							++errorCount;
							output.Text += string.Format("<b>{0}</b>", line);
						}
					}
					message += "[" + errorCount.ToString() + "]";
					if (warningCount > 0)
						//message = string.Format("{0} (and {1} warning{2})", message, warningCount, warningCount == 1 ? "" : "s");
						message = string.Format("{0} (si {1} problem{2} minor{2})", message, warningCount, warningCount == 1 ? "a" : "e");
					SetMessage(message, true);
					//return false; //wait, don't return yet, keep exporting to file (for check-ups)
				}
			}
			if (validationResult.Count == 0)
				validationResult.Add("N/A");

			string sFileName;
			if (data.Tables.Count > 0 && data.Tables[0].Rows.Count > 0)
				sFileName = data.Tables[0].Rows[0]["FileName"].ToString();
			else
				throw new ApplicationException("Inconsistent data returned from the database. Name for the output file was not given!");
				//OR: sFileName = System.IO.Path.GetTempFileName();

			string sFilePath = parameters.LocateTargetFolder() + @"\" + sFileName;
			validationXSDFile = parameters.GetXSDValidationFile();

            FileStream fs = new FileStream(sFilePath, FileMode.Create);
            System.Xml.XmlTextWriter objWriter = new System.Xml.XmlTextWriter(fs, new System.Text.UTF8Encoding(false));
			objWriter.WriteStartDocument(true);
			
			delegatedWriter(data, parameters, objWriter);

			objWriter.Flush();

			if (emptyAttributes > 0)
				ShowWarning("<b><u>Exportul a furnizat informatii incomplete.</u></b> <br/>Continut lipsa: " + emptyAttributes);

			if (shouldValidateXsd & chkValidation.Checked)
				ValidateXMLByXSD(fs);
			if (objWriter.BaseStream.CanRead) //otherwise would probably throw a System.ObjectDisposedException {"Cannot access a closed file."}
				objWriter.Close();
			fs.Close();
			return shouldValidateXsd ? ExportStatus.GeneratedOk : ExportStatus.FailedButGenerated;
		}
		catch (Exception ex)
		{
			this.SetMessage(ex.Message, true);
			output.Text = "e" + Tools.HiddenExceptionDetails(ex);
			return ExportStatus.NotGenerated;
		}
	}

	#region validation delegates
	private bool CounterValidator(DataSet data, out List<string> details)
	{
		//TODO: the specifics should be in a "ValidationDetails" table coming inside the DataSet :)

		DataTable centralizator = data.Tables[5];
		Dictionary<string, int> casesNumber = new Dictionary<string, int>();
		foreach (DataRow row in centralizator.Rows)
		{
			string deptCode = row["hospitalDeptCode"].ToString();
			int currentNumberOfCases = System.Convert.ToInt32(row["realisedCasesNo"]);
			if(casesNumber.ContainsKey(deptCode))
				casesNumber[deptCode] += currentNumberOfCases;
			else
				casesNumber[deptCode] = currentNumberOfCases;
			//OR: casesNumber[deptCode] = currentNumberOfCases + (casesNumber.ContainsKey(deptCode) ? casesNumber[deptCode] : 0);
		}

		Dictionary<string, List<string>> caseIds = new Dictionary<string, List<string>>(casesNumber.Count);
		foreach (string deptCode in casesNumber.Keys) caseIds[deptCode] = new List<string>(casesNumber[deptCode]);

		details = new List<string>();

		DataTable desfasurator = data.Tables[4];
		foreach (DataRow row in desfasurator.Rows)
		{
			string currentDeptCode = row["hospitalDeptCode"].ToString(),
				currentCaseId = row["case_id"].ToString();
			if (!casesNumber.ContainsKey(currentDeptCode))
				//details.Add(string.Format("(WARNING: Unknown deptCode: {0} for PID: {1} / CaseId: {2}!){3}", currentDeptCode, row["pid"], currentCaseId, System.Environment.NewLine));
				details.Add(string.Format("(Nota: Valoare deptCode incorecta: {0} la PID = {1} / CaseId = {2}!){3}", currentDeptCode, row["pid"], currentCaseId, System.Environment.NewLine));
			else
				if (!caseIds[currentDeptCode].Contains(currentCaseId))
					caseIds[currentDeptCode].Add(currentCaseId);
		}

		DataTable desfasuratorForeign = data.Tables[3];
		foreach (DataRow row in desfasuratorForeign.Rows)
		{
			string currentDeptCode = row["hospitalDeptCode"].ToString(),
				currentCaseId = row["caseId"].ToString();
			if (!casesNumber.ContainsKey(currentDeptCode))
				//details.Add(string.Format("(WARNING: Unknown deptCode: {0} for ForeignPID: {1} / CaseId: {2}!){3}", currentDeptCode, row["personIdentifier"], currentCaseId, System.Environment.NewLine));
				details.Add(string.Format("(Nota: Valoare deptCode incorecta: {0} la ForeignPID = {1} / CaseId = {2}!){3}", currentDeptCode, row["personIdentifier"], currentCaseId, System.Environment.NewLine));
			else
				if (!caseIds[currentDeptCode].Contains(currentCaseId))
					caseIds[currentDeptCode].Add(currentCaseId);
		}

		bool resultOk = true; //optimistic initialization :D
		foreach (string deptCode in casesNumber.Keys)
			if (casesNumber[deptCode] != caseIds[deptCode].Count)
			{
				//details.Add(string.Format("ERROR: {0} reports {1} but enumerates {2}.{3}", deptCode, casesNumber[deptCode], caseIds[deptCode].Count, System.Environment.NewLine));
				details.Add(string.Format("EROARE: Departamentul {0} centralizeaza {1} dar detaliaza {2}.{3}", deptCode, casesNumber[deptCode], caseIds[deptCode].Count, System.Environment.NewLine));
				resultOk = false;
			}
		if (resultOk) //show specific info o:-)
			switch (casesNumber.Count)
			{
				case 0:
					//details.Add("No hospitalDepts to check. Test OK?");
					details.Add("Niciun 'hospitalDept' de verificat. Presupunere implicita: OK?");
					break;
				case 1:
					//details.Add("The single hospitalDept has matched its reported and actual counts. Test OK.");
					details.Add("Singurul 'hospitalDept' gasit a fost validat, numarul raportat si cel efectiv coincid. Testul e OK.");
					break;
				default:
					//details.Add(string.Format("All {0} hospitalDepts have matched the reported and actual counts. Test OK.", casesNumber.Count));
					details.Add(string.Format("Toate {0} 'hospitalDept'-urile au fost validate, numerele raportate si cele efective coincid. Testul e OK.", casesNumber.Count));
					break;
			}
		return resultOk;
	}

	private void WriteAttributeString(System.Xml.XmlTextWriter objWriter, string attributeName, string attributeValue)
	{
		if (string.IsNullOrEmpty(attributeValue))
			++emptyAttributes;
		objWriter.WriteAttributeString(attributeName, attributeValue);
	}
	#endregion

	private void ShowWarning(string message)
	{
		//TODO: show as popup, for longer availability
		SetMessage(message.RemoveHtml(), true);
	}

	#region delegates that write the actual XML
	private void DoExportSIUI_1(DataSet ds_ExportClinic, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;

		objWriter.WriteStartElement("report");
		WriteAttributeString(objWriter, "xmlns", "http://localhost");
		WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(parameters.startDate).ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(parameters.endDate).ToString("yyyy-MM-dd"));

        if (ds_ExportClinic.Tables.Count > 0 && ds_ExportClinic.Tables[0].Rows.Count > 0)
        {
			WriteAttributeString(objWriter, "AppID", ds_ExportClinic.Tables[0].Rows[0]["appId"].ToString());
			WriteAttributeString(objWriter, "clinic", ds_ExportClinic.Tables[0].Rows[0]["clinic"].ToString());
			WriteAttributeString(objWriter, "fiscalCode", ds_ExportClinic.Tables[0].Rows[0]["fiscalCode"].ToString());
			WriteAttributeString(objWriter, "contractNo", ds_ExportClinic.Tables[0].Rows[0]["contractNo"].ToString());
			WriteAttributeString(objWriter, "insuranceHouse", ds_ExportClinic.Tables[0].Rows[0]["insuranceHouse"].ToString());

			WriteAttributeString(objWriter, "invoiceNo", ds_ExportClinic.Tables[0].Rows[0]["invoiceNo"].ToString());

			WriteAttributeString(objWriter, "labValue", ds_ExportClinic.Tables[0].Rows[0]["labValue"].ToString());
			WriteAttributeString(objWriter, "hspValue", ds_ExportClinic.Tables[0].Rows[0]["hspValue"].ToString());
        }

        #region clinicServices

        if (ds_ExportClinic.Tables.Count > 1 && ds_ExportClinic.Tables[1].Rows.Count > 0)
        {
            //start laboratoriesServices
            objWriter.WriteStartElement("clinicServices", null);
            for (int i = 0; i < ds_ExportClinic.Tables[1].Rows.Count; i++)
            {
                #region clinicService
                objWriter.WriteStartElement("clinicService", null);

				WriteAttributeString(objWriter, "AppID", ds_ExportClinic.Tables[1].Rows[i]["appId"].ToString());
				WriteAttributeString(objWriter, "stencilNo", ds_ExportClinic.Tables[1].Rows[i]["stencilNo"].ToString());
				WriteAttributeString(objWriter, "personPID", ds_ExportClinic.Tables[1].Rows[i]["personPID"].ToString());
				WriteAttributeString(objWriter, "patientInsuranceHouse", ds_ExportClinic.Tables[1].Rows[i]["patientInsuranceHouse"].ToString());
				WriteAttributeString(objWriter, "reportedService", ds_ExportClinic.Tables[1].Rows[i]["reportedService"].ToString());
				WriteAttributeString(objWriter, "medSrvPack", ds_ExportClinic.Tables[1].Rows[i]["medSrvPack"].ToString());
				WriteAttributeString(objWriter, "quantity", ds_ExportClinic.Tables[1].Rows[i]["quantity"].ToString());
				WriteAttributeString(objWriter, "serviceDate", Convert.ToDateTime(ds_ExportClinic.Tables[1].Rows[i]["serviceDate"]).ToString("yyyy-MM-dd"));
				WriteAttributeString(objWriter, "merNo", ds_ExportClinic.Tables[1].Rows[i]["merNo"].ToString());
				WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(ds_ExportClinic.Tables[1].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));
				WriteAttributeString(objWriter, "initialDiagnostic", ds_ExportClinic.Tables[1].Rows[i]["initialDiagnostic"].ToString());
				WriteAttributeString(objWriter, "confirmedDiagnostic", ds_ExportClinic.Tables[1].Rows[i]["confirmedDiagnostic"].ToString());
				WriteAttributeString(objWriter, "presentationMode", ds_ExportClinic.Tables[1].Rows[i]["presentationMode"].ToString());

                //if (ds.Tables[1].Rows[i]["serviceType"].ToString() != "")
				WriteAttributeString(objWriter, "serviceType", ds_ExportClinic.Tables[1].Rows[i]["serviceType"].ToString());
                //if (ds.Tables[1].Rows[i]["serviceHour"].ToString() != "")
				WriteAttributeString(objWriter, "serviceHour", ds_ExportClinic.Tables[1].Rows[i]["serviceHour"].ToString());
                //if (ds.Tables[1].Rows[i]["diseaseType"].ToString() != "")
				WriteAttributeString(objWriter, "diseaseType", ds_ExportClinic.Tables[1].Rows[i]["diseaseType"].ToString());

                //if (ds.Tables[1].Rows[i]["refferedByStencilNo"].ToString() != null)
				WriteAttributeString(objWriter, "refferedByStencilNo", ds_ExportClinic.Tables[1].Rows[i]["refferByStencilNo"].ToString());

                //if (ds.Tables[1].Rows[i]["refferedBySerialNo"].ToString() != "")
				WriteAttributeString(objWriter, "refferedBySerialNo", ds_ExportClinic.Tables[1].Rows[i]["refferedBySerialNo"].ToString());
                //if (ds.Tables[1].Rows[i]["refferedBySerialCode"].ToString() != "")
				WriteAttributeString(objWriter, "refferedBySerialCode", ds_ExportClinic.Tables[1].Rows[i]["refferedBySerialCode"].ToString());
                //if (ds.Tables[1].Rows[i]["refferedBySpecialty"].ToString() != "")
				WriteAttributeString(objWriter, "refferedBySpecialty", ds_ExportClinic.Tables[1].Rows[i]["refferedBySpecialty"].ToString());
                //if (ds.Tables[1].Rows[i]["refferedByDiagnostic"].ToString() != "")
				WriteAttributeString(objWriter, "refferedByDiagnostic", ds_ExportClinic.Tables[1].Rows[i]["refferedByDiagnostic"].ToString());
                //if (ds.Tables[1].Rows[i]["refferedByContractNo"].ToString() != "")
				WriteAttributeString(objWriter, "refferedByContractNo", ds_ExportClinic.Tables[1].Rows[i]["refferedByContractNo"].ToString());
                if (ds_ExportClinic.Tables[1].Rows[i]["refferedByDate"].ToString() != "")
					WriteAttributeString(objWriter, "refferedByDate", Convert.ToDateTime(ds_ExportClinic.Tables[1].Rows[i]["refferedByDate"]).ToString("yyyy-MM-dd"));

				WriteAttributeString(objWriter, "personType", ds_ExportClinic.Tables[1].Rows[i]["personType"].ToString());

                //end clinicService
                WriteCustomEndElement(objWriter);
                #endregion
            }
            //end laboratoriesServices
			WriteCustomEndElement(objWriter);
        }

        #endregion

        #region laboratoriesServices

        if (ds_ExportClinic.Tables.Count > 2 && ds_ExportClinic.Tables[2].Rows.Count > 0)
        {
            //start laboratoriesServices
            objWriter.WriteStartElement("laboratoriesServices", null);
            for (int i = 0; i < ds_ExportClinic.Tables[2].Rows.Count; i++)
            {
                #region laboratoriesService
                objWriter.WriteStartElement("laboratoriesService", null);

				WriteAttributeString(objWriter, "AppID", ds_ExportClinic.Tables[2].Rows[i]["appId"].ToString());
				WriteAttributeString(objWriter, "stencilNo", ds_ExportClinic.Tables[2].Rows[i]["stencilNo"].ToString());
				WriteAttributeString(objWriter, "personPID", ds_ExportClinic.Tables[2].Rows[i]["personPID"].ToString());
				WriteAttributeString(objWriter, "patientInsuranceHouse", ds_ExportClinic.Tables[2].Rows[i]["patientInsuranceHouse"].ToString());
				WriteAttributeString(objWriter, "reportedService", ds_ExportClinic.Tables[2].Rows[i]["reportedService"].ToString());
				WriteAttributeString(objWriter, "medSrvPack", ds_ExportClinic.Tables[2].Rows[i]["medSrvPack"].ToString());
				WriteAttributeString(objWriter, "quantity", ds_ExportClinic.Tables[2].Rows[i]["quantity"].ToString());
                WriteAttributeString(objWriter, "serviceDate", Convert.ToDateTime(ds_ExportClinic.Tables[2].Rows[i]["serviceDate"]).ToString("yyyy-MM-dd"));
                WriteAttributeString(objWriter, "merNo", ds_ExportClinic.Tables[2].Rows[i]["merNo"].ToString());
                WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(ds_ExportClinic.Tables[2].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));
                WriteAttributeString(objWriter, "diagnostic", ds_ExportClinic.Tables[2].Rows[i]["diagnostic"].ToString());
                WriteAttributeString(objWriter, "reportedTarrif", ds_ExportClinic.Tables[2].Rows[i]["reportedTarrif"].ToString());
                WriteAttributeString(objWriter, "refferedByStencilNo", ds_ExportClinic.Tables[2].Rows[i]["refferByStencilNo"].ToString());
                WriteAttributeString(objWriter, "refferedBySerialNo", ds_ExportClinic.Tables[2].Rows[i]["refferedBySerialNo"].ToString());
                WriteAttributeString(objWriter, "refferedBySerialCode", ds_ExportClinic.Tables[2].Rows[i]["refferedBySerialCode"].ToString());
                WriteAttributeString(objWriter, "refferedBySpecialty", ds_ExportClinic.Tables[2].Rows[i]["refferedBySpecialty"].ToString());
                WriteAttributeString(objWriter, "refferedByDiagnostic", ds_ExportClinic.Tables[2].Rows[i]["refferedByDiagnostic"].ToString());
                WriteAttributeString(objWriter, "refferedByContractNo", ds_ExportClinic.Tables[2].Rows[i]["refferedByContractNo"].ToString());
                if (ds_ExportClinic.Tables[2].Rows[i]["refferedByDate"].ToString() != "")
                    WriteAttributeString(objWriter, "refferedByDate", Convert.ToDateTime(ds_ExportClinic.Tables[2].Rows[i]["refferedByDate"]).ToString("yyyy-MM-dd"));
                WriteAttributeString(objWriter, "patientSource", ds_ExportClinic.Tables[2].Rows[i]["patientSource"].ToString());
                WriteAttributeString(objWriter, "refferedByPC", ds_ExportClinic.Tables[2].Rows[i]["refferedByPC"].ToString());
                WriteAttributeString(objWriter, "personType", ds_ExportClinic.Tables[2].Rows[i]["personType"].ToString());

                //end laboratoriesService
				WriteCustomEndElement(objWriter);
                #endregion
            }
            //end laboratoriesServices
			WriteCustomEndElement(objWriter);
        }

        #endregion

        #region dailyServices
        #endregion

        #region prescriptions

        string appID_p = "";
		int drugIndex = CounterStart;
        if (ds_ExportClinic.Tables.Count > 3 && ds_ExportClinic.Tables[3].Rows.Count > 0)
        {
            //start prescriptions
            objWriter.WriteStartElement("prescriptions", null);
            for (int i = 0; i < ds_ExportClinic.Tables[3].Rows.Count; i++)
            {
				string currentAppID = ds_ExportClinic.Tables[3].Rows[i]["appId"].ToString();
				if (appID_p != currentAppID) //new prescription
				{
					#region start current prescription element
					if (appID_p != "") //not first
                    {
						WriteCustomEndElement(objWriter); //close previous "prescription" element
						drugIndex = CounterStart; //reset drug index
                    }
                    #region prescription (no closing tag)
                    objWriter.WriteStartElement("prescription", null);

					WriteAttributeString(objWriter, "AppID", currentAppID);
                    WriteAttributeString(objWriter, "stencilNo", ds_ExportClinic.Tables[3].Rows[i]["stencilNo"].ToString());
                    WriteAttributeString(objWriter, "personPID", ds_ExportClinic.Tables[3].Rows[i]["personPID"].ToString());
                    WriteAttributeString(objWriter, "patientInsuranceHouse", ds_ExportClinic.Tables[3].Rows[i]["patientInsuranceHouse"].ToString());
                    WriteAttributeString(objWriter, "serialNo", ds_ExportClinic.Tables[3].Rows[i]["serialNo"].ToString());
                    WriteAttributeString(objWriter, "serialCode", ds_ExportClinic.Tables[3].Rows[i]["serialCode"].ToString());
                    WriteAttributeString(objWriter, "contractNo", ds_ExportClinic.Tables[3].Rows[i]["contractNo"].ToString());
                    WriteAttributeString(objWriter, "prescriptionDate", Convert.ToDateTime(ds_ExportClinic.Tables[3].Rows[i]["prescriptionDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "merNo", ds_ExportClinic.Tables[3].Rows[i]["merNo"].ToString());
                    WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(ds_ExportClinic.Tables[3].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "patientType", ds_ExportClinic.Tables[3].Rows[i]["patientType"].ToString());
                    WriteAttributeString(objWriter, "prescriptionType", ds_ExportClinic.Tables[3].Rows[i]["prescriptionType"].ToString());
					#endregion
					#endregion
				}
				#region prescriptionDrug
				objWriter.WriteStartElement("prescriptionDrug", null);

                WriteAttributeString(objWriter, "AppID", ds_ExportClinic.Tables[3].Rows[i]["appDrugId"].ToString());
				WriteAttributeString(objWriter, "no", drugIndex.ToString());
                WriteAttributeString(objWriter, "drugCode", ds_ExportClinic.Tables[3].Rows[i]["drugCode"].ToString());
                WriteAttributeString(objWriter, "activeSubstance", ds_ExportClinic.Tables[3].Rows[i]["activeSubstance"].ToString());
                WriteAttributeString(objWriter, "concentration", ds_ExportClinic.Tables[3].Rows[i]["concentration"].ToString());
                WriteAttributeString(objWriter, "diseaseCode", ds_ExportClinic.Tables[3].Rows[i]["diseaseCode"].ToString());
                if (ds_ExportClinic.Tables[3].Rows[i]["diseaseCategory"].ToString() != "")
                    WriteAttributeString(objWriter, "diseaseCategory", ds_ExportClinic.Tables[3].Rows[i]["diseaseCategory"].ToString());
                WriteAttributeString(objWriter, "pharmaceuticalForm", ds_ExportClinic.Tables[3].Rows[i]["pharmaceuticalForm"].ToString());
                WriteAttributeString(objWriter, "quantity", ds_ExportClinic.Tables[3].Rows[i]["quantity"].ToString());

				WriteCustomEndElement(objWriter);
				#endregion
				appID_p = currentAppID;
				drugIndex++;
            }
            //close final prescription element
			WriteCustomEndElement(objWriter);
            //end prescriptions
			WriteCustomEndElement(objWriter);
        }
        #endregion

        #region medicalNotes

        string appID_MN = "";
		List<string> arrDiagnostics = new List<string>();
		int mniIndex = CounterStart;
        if (ds_ExportClinic.Tables.Count > 4 && ds_ExportClinic.Tables[4].Rows.Count > 0)
        {
            objWriter.WriteStartElement("medicalNotes", null);
            for (int i = 0; i < ds_ExportClinic.Tables[4].Rows.Count; i++)
            {
				string currentAppId = ds_ExportClinic.Tables[4].Rows[i]["appId"].ToString();
				if (appID_MN != currentAppId) //new medicalNote
				{
					#region start current medicalNote element
					if (appID_MN != "") //not first
					{
						#region dump collected secondaryDiagnostics
						objWriter.WriteStartElement("secondaryDiagnostics", null);
						//if (arrDiagnostics.Count > 0)
                        {
							int diagIndex = CounterStart;
							foreach (string diagnostic in arrDiagnostics)
							{
								#region secondaryDiagnostic
								objWriter.WriteStartElement("secondaryDiagnostic", null);
								WriteAttributeString(objWriter, "no", diagIndex.ToString());
								WriteAttributeString(objWriter, "code", diagnostic);
								WriteCustomEndElement(objWriter);
								#endregion
								++diagIndex;
							}
							arrDiagnostics.Clear();
                        }
						WriteCustomEndElement(objWriter);
						#endregion
						WriteCustomEndElement(objWriter); // close previous "medicalNote" element
						mniIndex = CounterStart; //reset MedicalNoteInvestigation index
					}
                    #region medicalNote
                    objWriter.WriteStartElement("medicalNote", null);

					WriteAttributeString(objWriter, "AppID", currentAppId);
                    WriteAttributeString(objWriter, "stencilNo", ds_ExportClinic.Tables[4].Rows[i]["stencilNo"].ToString());
                    WriteAttributeString(objWriter, "personPID", ds_ExportClinic.Tables[4].Rows[i]["personPID"].ToString());
                    WriteAttributeString(objWriter, "patientInsuranceHouse", ds_ExportClinic.Tables[4].Rows[i]["patientInsuranceHouse"].ToString());
                    WriteAttributeString(objWriter, "serialNo", ds_ExportClinic.Tables[4].Rows[i]["serialNo"].ToString());
                    WriteAttributeString(objWriter, "serialCode", ds_ExportClinic.Tables[4].Rows[i]["serialCode"].ToString());
                    WriteAttributeString(objWriter, "issueDate", Convert.ToDateTime(ds_ExportClinic.Tables[4].Rows[i]["issueDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "merNo", ds_ExportClinic.Tables[4].Rows[i]["merNo"].ToString());
                    WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(ds_ExportClinic.Tables[4].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "ticketType", ds_ExportClinic.Tables[4].Rows[i]["ticketType"].ToString());
                    WriteAttributeString(objWriter, "diagnostic", ds_ExportClinic.Tables[4].Rows[i]["diagnostic"].ToString());
                    //if (ds.Tables[4].Rows[i]["speciality"].ToString() != "")
                    WriteAttributeString(objWriter, "specialty", ds_ExportClinic.Tables[4].Rows[i]["speciality"].ToString());
                    WriteAttributeString(objWriter, "personType", ds_ExportClinic.Tables[4].Rows[i]["personType"].ToString());
					#endregion
					#endregion
				}
                if (ds_ExportClinic.Tables[4].Rows[i]["appServiceID"].ToString() != "")
				{
					#region medicalNoteInvestigation
					objWriter.WriteStartElement("medicalNoteInvestigation", null);

                    WriteAttributeString(objWriter, "AppID", ds_ExportClinic.Tables[4].Rows[i]["appServiceID"].ToString());
                    WriteAttributeString(objWriter, "no", mniIndex.ToString());
                    WriteAttributeString(objWriter, "investigation", ds_ExportClinic.Tables[4].Rows[i]["investigation"].ToString());
                    WriteAttributeString(objWriter, "quantity", ds_ExportClinic.Tables[4].Rows[i]["quantity"].ToString());

					WriteCustomEndElement(objWriter);
					#endregion
				}
				#region collect secondary diagnostics
				if (ds_ExportClinic.Tables[4].Rows[i]["appDiagnosticID"].ToString() != "")
					arrDiagnostics.Add(ds_ExportClinic.Tables[4].Rows[i]["SenderDiagCode"].ToString());
				#endregion

				appID_MN = currentAppId;
                ++mniIndex;
            }
			//close final medicalNote element
			WriteCustomEndElement(objWriter);
            //end medicalNotes
			WriteCustomEndElement(objWriter);
        }

        #endregion

        //end report
		WriteCustomEndElement(objWriter);
    }

	private void DoExportSIUI_2(DataSet ds_FarmacieCI, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;

		objWriter.WriteStartElement("report");
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(parameters.startDate).ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(parameters.endDate).ToString("yyyy-MM-dd"));
        if (ds_FarmacieCI.Tables.Count > 0 && ds_FarmacieCI.Tables[0].Rows.Count > 0)
        {
            WriteAttributeString(objWriter, "AppID", ds_FarmacieCI.Tables[0].Rows[0]["appId"].ToString());
            WriteAttributeString(objWriter, "pharmacy", ds_FarmacieCI.Tables[0].Rows[0]["pharmacy"].ToString());
            WriteAttributeString(objWriter, "fiscalCode", ds_FarmacieCI.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "contractNo", ds_FarmacieCI.Tables[0].Rows[0]["contractNo"].ToString());
            WriteAttributeString(objWriter, "insuranceHouse", ds_FarmacieCI.Tables[0].Rows[0]["insuranceHouse"].ToString());
        }

        #region hospitalRegister
        string appID = "";
        int j = 1;
        if (ds_FarmacieCI.Tables.Count > 1 && ds_FarmacieCI.Tables[1].Rows.Count > 0)
        {
            for (int i = 0; i < ds_FarmacieCI.Tables[1].Rows.Count; i++)
            {

                if (appID != ds_FarmacieCI.Tables[1].Rows[i]["appId"].ToString())
                {
                    if (appID != "")
                    {
						WriteCustomEndElement(objWriter);
                        j = 1;
                    }
                    #region hospitalRegister
                    objWriter.WriteStartElement("hospitalRegister", null);

                    WriteAttributeString(objWriter, "AppID", ds_FarmacieCI.Tables[1].Rows[i]["appId"].ToString());
                    WriteAttributeString(objWriter, "hospRegDate", Convert.ToDateTime(ds_FarmacieCI.Tables[1].Rows[i]["hospRegDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "chiefPhysicianContract", ds_FarmacieCI.Tables[1].Rows[i]["chiefPhysicianContract"].ToString());
                    WriteAttributeString(objWriter, "chiefPhysicianStencil", ds_FarmacieCI.Tables[1].Rows[i]["chiefPhysicianStencil"].ToString());
                    WriteAttributeString(objWriter, "hospRegNo", ds_FarmacieCI.Tables[1].Rows[i]["hospRegNo"].ToString());
                    WriteAttributeString(objWriter, "healthDepartment", ds_FarmacieCI.Tables[1].Rows[i]["healthDepartment"].ToString());
                    WriteAttributeString(objWriter, "isPrescription", ds_FarmacieCI.Tables[1].Rows[i]["isPrescription"].ToString());
                    #endregion
                }
                #region hospRegDrug
                objWriter.WriteStartElement("hospRegDrug", null);

                WriteAttributeString(objWriter, "AppID", ds_FarmacieCI.Tables[1].Rows[i]["appGdId"].ToString());
                WriteAttributeString(objWriter, "pos", j.ToString());
                WriteAttributeString(objWriter, "supplyCode", ds_FarmacieCI.Tables[1].Rows[i]["supplyCode"].ToString());
                WriteAttributeString(objWriter, "quantity", ds_FarmacieCI.Tables[1].Rows[i]["quantity"].ToString());
                WriteAttributeString(objWriter, "retailPrice", ds_FarmacieCI.Tables[1].Rows[i]["retailPrice"].ToString());
                WriteAttributeString(objWriter, "personPID", ds_FarmacieCI.Tables[1].Rows[i]["personPID"].ToString());
                //WriteAttributeString(objWriter, "diseaseCode", "10");
                WriteAttributeString(objWriter, "diseaseCode", ds_FarmacieCI.Tables[1].Rows[i]["diseaseCode"].ToString());
                if (ds_FarmacieCI.Tables[1].Rows[i]["nhpNo"].ToString() != "")
                    if (ds_FarmacieCI.Tables[1].Rows[i]["nhpNo"].ToString().Trim() != "0")
                        WriteAttributeString(objWriter, "nhpNo", ds_FarmacieCI.Tables[1].Rows[i]["NhpNo"].ToString());
                if (ds_FarmacieCI.Tables[1].Rows[i]["nhpCategory"].ToString() != "")
                    WriteAttributeString(objWriter, "nhpCategory", ds_FarmacieCI.Tables[1].Rows[i]["nhpCategory"].ToString());
                WriteAttributeString(objWriter, "patientInsuranceHouse", ds_FarmacieCI.Tables[1].Rows[i]["patientInsuranceHouse"].ToString());
                WriteAttributeString(objWriter, "merNo", ds_FarmacieCI.Tables[1].Rows[i]["merNo"].ToString());
                WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(ds_FarmacieCI.Tables[1].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));
                WriteAttributeString(objWriter, "physicianContract", ds_FarmacieCI.Tables[1].Rows[i]["physicianContract"].ToString());
                WriteAttributeString(objWriter, "physicianStencil", ds_FarmacieCI.Tables[1].Rows[i]["physicianStencil"].ToString());
                WriteAttributeString(objWriter, "isInsured", ds_FarmacieCI.Tables[1].Rows[i]["isInsured"].ToString());
                WriteAttributeString(objWriter, "supplyType", ds_FarmacieCI.Tables[1].Rows[i]["supplyType"].ToString());

				WriteCustomEndElement(objWriter);
                #endregion
                appID = ds_FarmacieCI.Tables[1].Rows[i]["appId"].ToString();
                j++;
            }
			WriteCustomEndElement(objWriter);
        }

        #endregion

		//end report
		WriteCustomEndElement(objWriter);
    }

	private void DoExportSIUI_3(DataSet ds_Spital_DRG, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;

		#region opening of report tag
		objWriter.WriteStartElement("report");
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "startFrom", parameters.StartDate.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "endTo", parameters.EndDate.ToString("yyyy-MM-dd"));
        if (ds_Spital_DRG.Tables.Count > 0 && ds_Spital_DRG.Tables[0].Rows.Count > 0)
        {
            WriteAttributeString(objWriter, "hospitalCode", ds_Spital_DRG.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "fiscalCode", ds_Spital_DRG.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "insuranceHouse", ds_Spital_DRG.Tables[0].Rows[0]["insuranceHouse"].ToString());
            WriteAttributeString(objWriter, "contractNo", ds_Spital_DRG.Tables[0].Rows[0]["contractNo"].ToString());
            WriteAttributeString(objWriter, "AppID", ds_Spital_DRG.Tables[0].Rows[0]["appId"].ToString());
		}
		#endregion

		#region DRGS

		objWriter.WriteStartElement("DRGS", null);
        if (ds_Spital_DRG.Tables.Count > 5 && ds_Spital_DRG.Tables[5].Rows.Count > 0)
        {
            for (int i = 0; i < ds_Spital_DRG.Tables[5].Rows.Count; i++)
            {
                #region DRG
                objWriter.WriteStartElement("DRG", null);


                WriteAttributeString(objWriter, "AppID", Convert.ToString((i + 1)));
                WriteAttributeString(objWriter, "hospitalDeptCode", ds_Spital_DRG.Tables[5].Rows[i]["hospitalDeptCode"].ToString());
                WriteAttributeString(objWriter, "averageCasesNo", Tools.GetNumberInEnglishFormat(ds_Spital_DRG.Tables[5].Rows[i]["averageCasesNo"].ToString()));

                //if (ds.Tables[5].Rows[i]["coefK"].ToString() != "") 
                WriteAttributeString(objWriter, "coefK", ds_Spital_DRG.Tables[5].Rows[i]["coefK"].ToString());

                WriteAttributeString(objWriter, "icmRealizat", Tools.GetNumberInEnglishFormat(ds_Spital_DRG.Tables[5].Rows[i]["icmRealizat"].ToString()));
                WriteAttributeString(objWriter, "invalidatedCasesNo", ds_Spital_DRG.Tables[5].Rows[i]["invalidatedCasesNo"].ToString());
                WriteAttributeString(objWriter, "realisedAmount", Tools.GetNumberInEnglishFormat(ds_Spital_DRG.Tables[5].Rows[i]["realisedAmount"].ToString()));
                WriteAttributeString(objWriter, "realisedCasesNo", ds_Spital_DRG.Tables[5].Rows[i]["realisedCasesNo"].ToString());
                WriteAttributeString(objWriter, "validatedCasesNo", ds_Spital_DRG.Tables[5].Rows[i]["validatedCasesNo"].ToString());
                WriteAttributeString(objWriter, "personType", ds_Spital_DRG.Tables[5].Rows[i]["personType"].ToString());
                WriteAttributeString(objWriter, "tcp", ds_Spital_DRG.Tables[5].Rows[i]["tcp"].ToString());
                if (ds_Spital_DRG.Tables[5].Rows[i]["fromDate"].ToString() != "")
                    WriteAttributeString(objWriter, "fromDate", Convert.ToDateTime(ds_Spital_DRG.Tables[5].Rows[i]["fromDate"]).ToString("yyyy-MM-dd"));
                if (ds_Spital_DRG.Tables[5].Rows[i]["toDate"].ToString() != "")
                    WriteAttributeString(objWriter, "toDate", Convert.ToDateTime(ds_Spital_DRG.Tables[5].Rows[i]["toDate"]).ToString("yyyy-MM-dd"));
                if (ds_Spital_DRG.Tables[5].Rows[i]["transferredCasesNo"].ToString() != "")
                    WriteAttributeString(objWriter, "transferredCasesNo", ds_Spital_DRG.Tables[5].Rows[i]["transferredCasesNo"].ToString());

                //end DRG 
				WriteCustomEndElement(objWriter);

                #endregion
            }
        }

        //end DRGS
		WriteCustomEndElement(objWriter);

        #endregion

        #region DRGPrescriptions

        string appID = "";
        int j = 1;
        if (ds_Spital_DRG.Tables.Count > 1 && ds_Spital_DRG.Tables[1].Rows.Count > 0)
        {
            objWriter.WriteStartElement("DRGPrescriptions", null);
            for (int i = 0; i < ds_Spital_DRG.Tables[1].Rows.Count; i++)
            {

                if (appID != ds_Spital_DRG.Tables[1].Rows[i]["appId"].ToString())
                {
                    if (appID != "")
                    {
						WriteCustomEndElement(objWriter);
						j = 1;
                    }
                    #region DRGPrescription
                    objWriter.WriteStartElement("DRGPrescription", null);

                    WriteAttributeString(objWriter, "AppID", ds_Spital_DRG.Tables[1].Rows[i]["appId"].ToString());
                    WriteAttributeString(objWriter, "stencilNo", ds_Spital_DRG.Tables[1].Rows[i]["stencilNo"].ToString());
                    WriteAttributeString(objWriter, "personPID", ds_Spital_DRG.Tables[1].Rows[i]["personPID"].ToString());
                    WriteAttributeString(objWriter, "patientInsuranceHouse",
                                                   ds_Spital_DRG.Tables[1].Rows[i]["patientInsuranceHouse"].ToString());
                    WriteAttributeString(objWriter, "serialNo", ds_Spital_DRG.Tables[1].Rows[i]["serialNo"].ToString());
                    WriteAttributeString(objWriter, "serialCode", ds_Spital_DRG.Tables[1].Rows[i]["serialCode"].ToString());
                    WriteAttributeString(objWriter, "contractNo", ds_Spital_DRG.Tables[1].Rows[i]["contractNo"].ToString());
                    WriteAttributeString(objWriter, "prescriptionDate",
                                                   Convert.ToDateTime(ds_Spital_DRG.Tables[1].Rows[i]["prescriptionDate"]).ToString(
                                                    "yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "merNo", ds_Spital_DRG.Tables[1].Rows[i]["merNo"].ToString());
                    WriteAttributeString(objWriter, "merDate",
                                                   Convert.ToDateTime(ds_Spital_DRG.Tables[1].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));
                    //WriteAttributeString(objWriter, "no", "");
                    //WriteAttributeString(objWriter, "nhp", "");
                    WriteAttributeString(objWriter, "patientType", ds_Spital_DRG.Tables[1].Rows[i]["patientType"].ToString());
                    WriteAttributeString(objWriter, "prescriptionType", ds_Spital_DRG.Tables[1].Rows[i]["prescriptionType"].ToString());
                    WriteAttributeString(objWriter, "noDaysTreatment", ds_Spital_DRG.Tables[1].Rows[i]["noDaysTreatment"].ToString());
                    #endregion

                }

                #region DRGPrescDrug
                objWriter.WriteStartElement("DRGPrescDrug", null);

                WriteAttributeString(objWriter, "no", j.ToString());
                WriteAttributeString(objWriter, "drugCode", ds_Spital_DRG.Tables[1].Rows[i]["drugCode"].ToString());
                WriteAttributeString(objWriter, "activeSubstance", ds_Spital_DRG.Tables[1].Rows[i]["activeSubstance"].ToString());
                if (ds_Spital_DRG.Tables[1].Rows[i]["concentration"].ToString() != "")
                    WriteAttributeString(objWriter, "concentration", ds_Spital_DRG.Tables[1].Rows[i]["concentration"].ToString());
                WriteAttributeString(objWriter, "diseaseCode", ds_Spital_DRG.Tables[1].Rows[i]["diseaseCode"].ToString());
                if (ds_Spital_DRG.Tables[1].Rows[i]["diseaseCategory"].ToString() != "")
                    WriteAttributeString(objWriter, "diseaseCategory", ds_Spital_DRG.Tables[1].Rows[i]["diseaseCategory"].ToString());
                WriteAttributeString(objWriter, "pharmaceuticalForm", ds_Spital_DRG.Tables[1].Rows[i]["pharmaceuticalForm"].ToString());
                WriteAttributeString(objWriter, "quantity", ds_Spital_DRG.Tables[1].Rows[i]["quantity"].ToString());
                WriteAttributeString(objWriter, "diagnosticType", ds_Spital_DRG.Tables[1].Rows[i]["diagnosticType"].ToString());

				WriteCustomEndElement(objWriter);

                appID = ds_Spital_DRG.Tables[1].Rows[i]["appId"].ToString();
                j++;
                #endregion
            }
            //end prescription
			WriteCustomEndElement(objWriter);
			//end prescriptions
			WriteCustomEndElement(objWriter);
		}

        #endregion

        #region DRGMedicalNotes

        if (ds_Spital_DRG.Tables.Count > 2 && ds_Spital_DRG.Tables[2].Rows.Count > 0)
        {
            objWriter.WriteStartElement("DRGMedicalNotes", null);
            for (int i = 0; i < ds_Spital_DRG.Tables[2].Rows.Count; i++)
            {
                #region DRGMedicalNote
                objWriter.WriteStartElement("DRGMedicalNote ", null);

                WriteAttributeString(objWriter, "AppID", ds_Spital_DRG.Tables[2].Rows[i]["appId"].ToString());
                WriteAttributeString(objWriter, "stencilNo", ds_Spital_DRG.Tables[2].Rows[i]["stencilNo"].ToString());
                WriteAttributeString(objWriter, "personPID", ds_Spital_DRG.Tables[2].Rows[i]["personPID"].ToString());
                WriteAttributeString(objWriter, "patientInsuranceHouse", ds_Spital_DRG.Tables[2].Rows[i]["patientInsuranceHouse"].ToString());
                WriteAttributeString(objWriter, "serialNo", ds_Spital_DRG.Tables[2].Rows[i]["serialNo"].ToString());
                WriteAttributeString(objWriter, "serialCode", ds_Spital_DRG.Tables[2].Rows[i]["serialCode"].ToString());
                WriteAttributeString(objWriter, "issueDate", Convert.ToDateTime(ds_Spital_DRG.Tables[2].Rows[i]["issueDate"]).ToString("yyyy-MM-dd"));
                WriteAttributeString(objWriter, "merNo", ds_Spital_DRG.Tables[2].Rows[i]["merNo"].ToString());
                WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(ds_Spital_DRG.Tables[2].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));
                WriteAttributeString(objWriter, "ticketType", ds_Spital_DRG.Tables[2].Rows[i]["ticketType"].ToString());
                WriteAttributeString(objWriter, "no", ds_Spital_DRG.Tables[2].Rows[i]["appId"].ToString());
                WriteAttributeString(objWriter, "diagnostic", ds_Spital_DRG.Tables[2].Rows[i]["diagnostic"].ToString());
                WriteAttributeString(objWriter, "specialty", ds_Spital_DRG.Tables[2].Rows[i]["specialty"].ToString());

                //end DRGMedicalNote
				WriteCustomEndElement(objWriter);
				#endregion
            }
            //end DRGMedicalNotes
			WriteCustomEndElement(objWriter);
		}

        #endregion

        #region ForeignPersons

        string personIdentifier = "";
        int j2 = 1;
        if (ds_Spital_DRG.Tables.Count > 3 && ds_Spital_DRG.Tables[3].Rows.Count > 0)
        {
            objWriter.WriteStartElement("ForeignPersons", null);
            for (int i = 0; i < ds_Spital_DRG.Tables[3].Rows.Count; i++)
            {
				if (personIdentifier != ds_Spital_DRG.Tables[3].Rows[i]["caseId"].ToString())
                {
                    if (personIdentifier != "")
                    {
						WriteCustomEndElement(objWriter);
						j2 = 1;
                    }

                    #region ForeignPerson
                    objWriter.WriteStartElement("ForeignPerson", null);


                    WriteAttributeString(objWriter, "personIdentifier", ds_Spital_DRG.Tables[3].Rows[i]["personIdentifier"].ToString());
                    WriteAttributeString(objWriter, "personFirstName", ds_Spital_DRG.Tables[3].Rows[i]["personFirstName"].ToString());
                    WriteAttributeString(objWriter, "personLastName", ds_Spital_DRG.Tables[3].Rows[i]["personLastName"].ToString());
                    WriteAttributeString(objWriter, "birthDate", Convert.ToDateTime(ds_Spital_DRG.Tables[3].Rows[i]["birthDate"]).ToString("yyyy-MM-dd"));

                    if (ds_Spital_DRG.Tables[3].Rows[i]["countryCode"].ToString() != "")
                        WriteAttributeString(objWriter, "countryCode", ds_Spital_DRG.Tables[3].Rows[i]["countryCode"].ToString());

                    if (ds_Spital_DRG.Tables[3].Rows[i]["cardCode"].ToString() != "")
						WriteAttributeString(objWriter, "cardCode", ds_Spital_DRG.Tables[3].Rows[i]["cardCode"].ToString());

                    if (ds_Spital_DRG.Tables[3].Rows[i]["cardExpireDate"].ToString() != "")
                        WriteAttributeString(objWriter, "cardExpireDate", Convert.ToDateTime(ds_Spital_DRG.Tables[3].Rows[i]["cardExpireDate"]).ToString("yyyy-MM-dd"));

                    WriteAttributeString(objWriter, "caseId", ds_Spital_DRG.Tables[3].Rows[i]["caseId"].ToString());
                    WriteAttributeString(objWriter, "personType", ds_Spital_DRG.Tables[3].Rows[i]["personType"].ToString());
                    WriteAttributeString(objWriter, "internmentDate", Convert.ToDateTime(ds_Spital_DRG.Tables[3].Rows[i]["internmentDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "releaseDate", Convert.ToDateTime(ds_Spital_DRG.Tables[3].Rows[i]["releaseDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "hospitalDeptCode", ds_Spital_DRG.Tables[3].Rows[i]["hospitalDeptCode"].ToString());
				}

				#region ForeignProcedure
				if (ds_Spital_DRG.Tables[3].Rows[i]["procedureCode"].ToString() != "")
				{
					objWriter.WriteStartElement("ForeignProcedure", null);
					WriteAttributeString(objWriter, "procedureCode", ds_Spital_DRG.Tables[3].Rows[i]["procedureCode"].ToString());
					WriteCustomEndElement(objWriter);
				}
				#endregion

				personIdentifier = ds_Spital_DRG.Tables[3].Rows[i]["caseId"].ToString();
                j2++;

                    #endregion
            }
            //end ForeignPerson 
			WriteCustomEndElement(objWriter);
			//end ForeignPersons
			WriteCustomEndElement(objWriter);
		}

        #endregion

        #region PidLists

        objWriter.WriteStartElement("PidLists", null);
        string sheetNo = "";
        int j3 = 1;
        if (ds_Spital_DRG.Tables.Count > 4 && ds_Spital_DRG.Tables[4].Rows.Count > 0)
        {

            for (int i = 0; i < ds_Spital_DRG.Tables[4].Rows.Count; i++)
            {
                if (sheetNo != ds_Spital_DRG.Tables[4].Rows[i]["sheetNo"].ToString())
                {
                    if (sheetNo != "")
                    {
						WriteCustomEndElement(objWriter);
						j3 = 1;
                    }

					#region PidList
                    objWriter.WriteStartElement("PidList", null);


                    WriteAttributeString(objWriter, "AppID", ds_Spital_DRG.Tables[4].Rows[i]["AppID"].ToString());
                    WriteAttributeString(objWriter, "pid", ds_Spital_DRG.Tables[4].Rows[i]["pid"].ToString());
                    //WriteAttributeString(objWriter, "specialSituationCode", ds.Tables[4].Rows[i]["specialSituationCode"].ToString());

                    if (ds_Spital_DRG.Tables[4].Rows[i]["specialSituationCode"].ToString() != "")
                        WriteAttributeString(objWriter, "specialSituationCode", ds_Spital_DRG.Tables[4].Rows[i]["specialSituationCode"].ToString());

                    WriteAttributeString(objWriter, "birthDate", Convert.ToDateTime(ds_Spital_DRG.Tables[4].Rows[i]["birthdate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "internmentDate", Convert.ToDateTime(ds_Spital_DRG.Tables[4].Rows[i]["internmentDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "hospitalDeptCode", ds_Spital_DRG.Tables[4].Rows[i]["hospitalDeptCode"].ToString());
                    WriteAttributeString(objWriter, "releaseDate", Convert.ToDateTime(ds_Spital_DRG.Tables[4].Rows[i]["releaseDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "sheetNo", ds_Spital_DRG.Tables[4].Rows[i]["sheetNo"].ToString());
                    WriteAttributeString(objWriter, "case_id", ds_Spital_DRG.Tables[4].Rows[i]["case_id"].ToString());
                    WriteAttributeString(objWriter, "internmentCriteriaCode", ds_Spital_DRG.Tables[4].Rows[i]["internmentCriteriaCode"].ToString());
                    if (ds_Spital_DRG.Tables[4].Rows[i]["transferred"].ToString() != "")
                        WriteAttributeString(objWriter, "transferred", ds_Spital_DRG.Tables[4].Rows[i]["transferred"].ToString());
                    #endregion
                }
                #region Procedure
				if (ds_Spital_DRG.Tables[4].Rows[i]["procedureCode"].ToString() != "")
                {
                    objWriter.WriteStartElement("Procedure", null);
                    WriteAttributeString(objWriter, "procedureCode", ds_Spital_DRG.Tables[4].Rows[i]["procedureCode"].ToString());
					WriteCustomEndElement(objWriter);
				}
                #endregion
                sheetNo = ds_Spital_DRG.Tables[4].Rows[i]["sheetNo"].ToString();
                j3++;
            }
			WriteCustomEndElement(objWriter);

        }
		WriteCustomEndElement(objWriter);

        #region OtherSuppliers

        objWriter.WriteStartElement("OtherSuppliers", null);
        string sheetNo2 = "";
        int j4 = 1;
        if (ds_Spital_DRG.Tables.Count > 6 && ds_Spital_DRG.Tables[6].Rows.Count > 0)
        {

            for (int i = 0; i < ds_Spital_DRG.Tables[6].Rows.Count; i++)
            {
                if (sheetNo2 != ds_Spital_DRG.Tables[6].Rows[i]["sheetNo"].ToString())
                {
                    if (sheetNo2 != "")
                    {
						WriteCustomEndElement(objWriter);
						j4 = 1;
                    }
                    #region OtherSupplier
                    objWriter.WriteStartElement("OtherSupplier", null);


                    WriteAttributeString(objWriter, "AppID", ds_Spital_DRG.Tables[6].Rows[i]["AppID"].ToString());
                    if (ds_Spital_DRG.Tables[6].Rows[i]["personIdentifier"].ToString() != "")
                        WriteAttributeString(objWriter, "personIdentifier", ds_Spital_DRG.Tables[6].Rows[i]["personIdentifier"].ToString());
                    WriteAttributeString(objWriter, "serviceCode", ds_Spital_DRG.Tables[6].Rows[i]["serviceCode"].ToString());
                    WriteAttributeString(objWriter, "noServices", ds_Spital_DRG.Tables[6].Rows[i]["noServices"].ToString());
                    WriteAttributeString(objWriter, "tariff", ds_Spital_DRG.Tables[6].Rows[i]["tariff"].ToString());
                    WriteAttributeString(objWriter, "servicesData", Convert.ToDateTime(ds_Spital_DRG.Tables[6].Rows[i]["servicesData"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "supplierCode", ds_Spital_DRG.Tables[6].Rows[i]["supplierCode"].ToString());
                    WriteAttributeString(objWriter, "supplierContractNo", ds_Spital_DRG.Tables[6].Rows[i]["supplierContractNo"].ToString());
                    WriteAttributeString(objWriter, "serviceType", ds_Spital_DRG.Tables[6].Rows[i]["serviceType"].ToString());
                    WriteAttributeString(objWriter, "supplierOrgUnit", ds_Spital_DRG.Tables[6].Rows[i]["supplierOrgUnit"].ToString());
                    WriteAttributeString(objWriter, "sheetNo", ds_Spital_DRG.Tables[6].Rows[i]["sheetNo"].ToString());


                    #endregion
                }
                sheetNo2 = ds_Spital_DRG.Tables[6].Rows[i]["sheetNo"].ToString();
                j4++;
            }
			WriteCustomEndElement(objWriter);

        }

		WriteCustomEndElement(objWriter);

        #endregion
        #endregion

        //closing the report tag
		WriteCustomEndElement(objWriter);
    }

	private void DoExportSIUI_4(DataSet ds_Spz_AnalitycalReport, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;

		bool isValidContractPeriod = false;
        bool isValidDailyCasePeriod = true;
        bool isValidDailyServicePeriod = true;
        string[] arrDiagnostics = new string[100];
        string[] arrAppID = new string[100];
        string[] arrServices = new string[100];
        string[] arrServiceAppID = new string[100];
        string[] arrServicesDate = new string[100];

        if (ds_Spz_AnalitycalReport.Tables.Count > 4 && ds_Spz_AnalitycalReport.Tables[4].Rows.Count > 0)
        {
            isValidContractPeriod = (int)ds_Spz_AnalitycalReport.Tables[4].Rows[0]["counts"] > 0;
        }

        if (ds_Spz_AnalitycalReport.Tables.Count > 5 && ds_Spz_AnalitycalReport.Tables[5].Rows.Count > 0)
        {
            if ((int)ds_Spz_AnalitycalReport.Tables[5].Rows[0]["counts"] != -1)
                isValidDailyCasePeriod = (int)ds_Spz_AnalitycalReport.Tables[5].Rows[0]["counts"] > 0;
        }

        if (ds_Spz_AnalitycalReport.Tables.Count > 6 && ds_Spz_AnalitycalReport.Tables[6].Rows.Count > 0)
        {
            if ((int)ds_Spz_AnalitycalReport.Tables[6].Rows[0]["counts"] != -1)
                isValidDailyServicePeriod = (int)ds_Spz_AnalitycalReport.Tables[6].Rows[0]["counts"] > 0;
        }

        objWriter.WriteStartElement("report");
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(parameters.startDate).ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(parameters.endDate).ToString("yyyy-MM-dd"));
        if (ds_Spz_AnalitycalReport.Tables.Count > 0 && ds_Spz_AnalitycalReport.Tables[0].Rows.Count > 0)
        {
            WriteAttributeString(objWriter, "hospitalCode", ds_Spz_AnalitycalReport.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "fiscalCode", ds_Spz_AnalitycalReport.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "insuranceHouse", ds_Spz_AnalitycalReport.Tables[0].Rows[0]["insuranceHouse"].ToString());
            if (ds_Spz_AnalitycalReport.Tables[0].Rows[0]["invoiceNo"].ToString() != "")
                WriteAttributeString(objWriter, "invoiceNo", ds_Spz_AnalitycalReport.Tables[0].Rows[0]["invoiceNo"].ToString());
            if (ds_Spz_AnalitycalReport.Tables[0].Rows[0]["invoiceDate"].ToString() != "")
                WriteAttributeString(objWriter, "invoiceDate", Convert.ToDateTime(parameters.endDate).ToString("yyyy-MM-dd"));
            if (ds_Spz_AnalitycalReport.Tables[0].Rows[0]["invoiceValue"].ToString() != "")
                WriteAttributeString(objWriter, "invoiceValue", ds_Spz_AnalitycalReport.Tables[0].Rows[0]["invoiceNo"].ToString());
            WriteAttributeString(objWriter, "AppID", ds_Spz_AnalitycalReport.Tables[0].Rows[0]["AppId"].ToString());
            WriteAttributeString(objWriter, "contractNo", ds_Spz_AnalitycalReport.Tables[0].Rows[0]["contractNo"].ToString());
            WriteAttributeString(objWriter, "reportType", "SPZ");
        }

        #region Internships
        objWriter.WriteStartElement("Internships", null);

        string appInternID = "";
        string appServiceID = "";
        string appDiagID = "";
        int go = 1;
        int k = 1;
        int z = 1;
        if (ds_Spz_AnalitycalReport.Tables.Count > 1 && ds_Spz_AnalitycalReport.Tables[1].Rows.Count > 0)
        {
            //string appInternID ="";
            //string appServiceID = "";
            for (int i = 0; i < ds_Spz_AnalitycalReport.Tables[1].Rows.Count; i++)
            {
                if (appInternID != ds_Spz_AnalitycalReport.Tables[1].Rows[i]["AppID"].ToString())
                {
                    if (appInternID != "")
                    {
                        #region secondaryDiagnostics
                        if (k > 1)
                        {
                            for (int t = 1; t < k; t++)
                            {
                                objWriter.WriteStartElement("secondaryDiagnostics", null);

                                WriteAttributeString(objWriter, "AppID", arrAppID[t].ToString());
                                WriteAttributeString(objWriter, "secondaryDiagnostic", arrDiagnostics[t].ToString());
								WriteCustomEndElement(objWriter);
                            }
                            k = 1;
                            Array.Clear(arrDiagnostics, 0, arrDiagnostics.Length);
                            Array.Clear(arrAppID, 0, arrAppID.Length);
                        }
                        #endregion
                        #region services
                        if (z > 1)
                        {
                            for (int t = 1; t < z; t++)
                            {
                                objWriter.WriteStartElement("Services", null);
                                WriteAttributeString(objWriter, "AppID", arrServiceAppID[t].ToString());
                                WriteAttributeString(objWriter, "service", arrServices[t].ToString());
                                WriteAttributeString(objWriter, "serviceDate",
                                    Convert.ToDateTime(arrServicesDate[t]).ToString("yyyy-MM-dd"));
								WriteCustomEndElement(objWriter);
                            }
                            z = 1;
                            Array.Clear(arrServices, 0, arrServices.Length);
                            Array.Clear(arrServiceAppID, 0, arrServiceAppID.Length);
                            Array.Clear(arrServicesDate, 0, arrServicesDate.Length);
                        }
                        #endregion
                        #region ForeignPerson
                        //objWriter.WriteStartElement("ForeignPerson", null);
						//WriteCustomEndElement(objWriter);
                        #endregion
						WriteCustomEndElement(objWriter);
                        //j = 1;

                    }
                    #region Internship

                    objWriter.WriteStartElement("Internship", null);

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["AppID"].ToString() != "")
                        WriteAttributeString(objWriter, "AppID", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["AppID"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["medicalSheetNo"].ToString() != "")
                        WriteAttributeString(objWriter, "medicalSheetNo", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["medicalSheetNo"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["Pid"].ToString() != "")
                        WriteAttributeString(objWriter, "Pid", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["Pid"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["firstName"].ToString() != "")
                        WriteAttributeString(objWriter, "firstName", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["firstName"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["lastName"].ToString() != "")
                        WriteAttributeString(objWriter, "lastName", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["lastName"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["birthDate"].ToString() != "")
                        WriteAttributeString(objWriter, "birthDate",
                            Convert.ToDateTime(ds_Spz_AnalitycalReport.Tables[1].Rows[i]["birthDate"]).ToString("yyyy-MM-dd"));

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["sex"].ToString() != "")
                        WriteAttributeString(objWriter, "sex", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["sex"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["insuranceType"].ToString() != "")
                        WriteAttributeString(objWriter, "insuranceType", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["insuranceType"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["internmentDate"].ToString() != "")
                        WriteAttributeString(objWriter, "intermentDate",
                            Convert.ToDateTime(ds_Spz_AnalitycalReport.Tables[1].Rows[i]["internmentDate"]).ToString("yyyy-MM-dd"));

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["referringNo"].ToString() != "")
                        WriteAttributeString(objWriter, "referringNo", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["referringNo"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["referringStencilNo"].ToString() != "")
                        WriteAttributeString(objWriter, "referringStencilNo",
                            ds_Spz_AnalitycalReport.Tables[1].Rows[i]["referringStencilNo"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["referringCtr"].ToString() != "")
                        WriteAttributeString(objWriter, "referringCtr", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["referringCtr"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["referringDate"].ToString() != "")
                        WriteAttributeString(objWriter, "referringDate",
                            Convert.ToDateTime(ds_Spz_AnalitycalReport.Tables[1].Rows[i]["referringDate"]).ToString("yyyy-MM-dd"));

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["stencilNo"].ToString() != "")
                        WriteAttributeString(objWriter, "stencilNo", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["stencilNo"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["releasedDate"].ToString() != "")
                        WriteAttributeString(objWriter, "releasedDate",
                            Convert.ToDateTime(ds_Spz_AnalitycalReport.Tables[1].Rows[i]["releasedDate"]).ToString("yyyy-MM-dd"));

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["orgUnitCode"].ToString() != "")
                        WriteAttributeString(objWriter, "orgUnitCode", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["orgUnitCode"].ToString());


                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["internmentDiagCode"].ToString() != "")
                        WriteAttributeString(objWriter, "internmentDiagCode", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["internmentDiagCode"].ToString());


                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["mainDiagCode"].ToString() != "")
                        WriteAttributeString(objWriter, "mainDiagCode", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["mainDiagCode"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["at72hDiagCode"].ToString() != "")
                        WriteAttributeString(objWriter, "at72hDiagCode", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["at72hDiagCode"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["surgeonStencilNo"].ToString() != "")
                        WriteAttributeString(objWriter, "surgeonStencilNo", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["surgeonStencilNo"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["specialSituationCode"].ToString() != "")
                        WriteAttributeString(objWriter, "specialSituationCode",
                            ds_Spz_AnalitycalReport.Tables[1].Rows[i]["specialSituationCode"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["referringDiagCode"].ToString() != "")
                        WriteAttributeString(objWriter, "referringDiagCode",
                            ds_Spz_AnalitycalReport.Tables[1].Rows[i]["referringDiagCode"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["releaseType"].ToString() != "")
                        WriteAttributeString(objWriter, "releaseType",
                            ds_Spz_AnalitycalReport.Tables[1].Rows[i]["releaseType"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["internmentCriteriaCd"].ToString() != "")
                        WriteAttributeString(objWriter, "internmentCriteriaCd",
                            ds_Spz_AnalitycalReport.Tables[1].Rows[i]["internmentCriteriaCd"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["internmentType"].ToString() != "")
                        WriteAttributeString(objWriter, "internmentType", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["internmentType"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["IncdsReportingDate"].ToString() != "")
                        WriteAttributeString(objWriter, "IncdsReportingDate",
                            Convert.ToDateTime(ds_Spz_AnalitycalReport.Tables[1].Rows[i]["IncdsReportingDate"]).ToString("yyyy-MM-dd"));

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["caseId"].ToString() != "")
                        WriteAttributeString(objWriter, "caseId", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["caseId"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["releaseState"].ToString() != "")
                        WriteAttributeString(objWriter, "releaseState", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["releaseState"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["standardDuration"].ToString() != "")
                        WriteAttributeString(objWriter, "standardDuration", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["standardDuration"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["internmentTime"].ToString() != "")
                        WriteAttributeString(objWriter, "internmentTime", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["internmentTime"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["tariffType"].ToString() != "")
                        WriteAttributeString(objWriter, "tariffType", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["tariffType"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["deptCode"].ToString() != "")
                        WriteAttributeString(objWriter, "deptCode", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["deptCode"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["city"].ToString() != "")
                        WriteAttributeString(objWriter, "city", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["city"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["district"].ToString() != "")
                        WriteAttributeString(objWriter, "district", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["district"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["categAsig"].ToString() != "")
                        WriteAttributeString(objWriter, "categAsig", ds_Spz_AnalitycalReport.Tables[1].Rows[i]["categAsig"].ToString());

                    objWriter.Flush();


                    #endregion
                }
                if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["seconderyDiagnostic"].ToString() != "")
                {
                    go = 1;
                    for (int r = 0; r < k; r++)
                    {
                        if (arrAppID[r] == ds_Spz_AnalitycalReport.Tables[1].Rows[i]["cosediag_AppID"].ToString())
                        {
                            go = 0;
                            r = k;
                        }
                    }
                    if (go == 1)
                    {
                        arrDiagnostics[k] = ds_Spz_AnalitycalReport.Tables[1].Rows[i]["seconderyDiagnostic"].ToString();
                        arrAppID[k] = ds_Spz_AnalitycalReport.Tables[1].Rows[i]["cosediag_AppID"].ToString();
                        k++;
                    }
                }

                if (ds_Spz_AnalitycalReport.Tables[1].Rows[i]["serv_AppID"].ToString() != ""
                    && appServiceID != ds_Spz_AnalitycalReport.Tables[1].Rows[i]["serv_AppID"].ToString())
                {
                    arrServices[z] = ds_Spz_AnalitycalReport.Tables[1].Rows[i]["procedureCode"].ToString();
                    arrServiceAppID[z] = ds_Spz_AnalitycalReport.Tables[1].Rows[i]["serv_AppID"].ToString();
                    arrServicesDate[z] = ds_Spz_AnalitycalReport.Tables[1].Rows[i]["serviceDate"].ToString();
                    z++;
                }

                appInternID = ds_Spz_AnalitycalReport.Tables[1].Rows[i]["AppID"].ToString();
                appServiceID = ds_Spz_AnalitycalReport.Tables[1].Rows[i]["serv_AppID"].ToString();
                appDiagID = ds_Spz_AnalitycalReport.Tables[1].Rows[i]["cosediag_AppID"].ToString();
                // end Internship


            }
            if (appInternID != "")
            {
                #region secondaryDiagnostics
                if (k > 1)
                {
                    for (int t = 1; t < k; t++)
                    {
                        objWriter.WriteStartElement("secondaryDiagnostics", null);
                        WriteAttributeString(objWriter, "AppID", arrAppID[t].ToString());
                        WriteAttributeString(objWriter, "secondaryDiagnostic", arrDiagnostics[t].ToString());
						WriteCustomEndElement(objWriter);
                    }
                    k = 1;
                    Array.Clear(arrDiagnostics, 0, arrDiagnostics.Length);
                    Array.Clear(arrAppID, 0, arrAppID.Length);
                }

                #endregion

                #region services
                if (z > 1)
                {
                    for (int t = 1; t < z; t++)
                    {
                        objWriter.WriteStartElement("Services", null);
                        WriteAttributeString(objWriter, "AppID", arrServiceAppID[t].ToString());
                        WriteAttributeString(objWriter, "service", arrServices[t].ToString());
                        WriteAttributeString(objWriter, "serviceDate", Convert.ToDateTime(arrServicesDate[t]).ToString("yyyy-MM-dd"));
						WriteCustomEndElement(objWriter);
                    }
                    z = 1;
                    Array.Clear(arrServices, 0, arrServices.Length);
                    Array.Clear(arrServiceAppID, 0, arrServiceAppID.Length);
                    Array.Clear(arrServicesDate, 0, arrServicesDate.Length);
                }
                #endregion

                #region ForeignPerson
                //objWriter.WriteStartElement("ForeignPerson", null);
				//WriteCustomEndElement(objWriter);
                #endregion

				WriteCustomEndElement(objWriter);
                //j = 1;

            }
        }

        //end Internships
		WriteCustomEndElement(objWriter);
        objWriter.Flush();
        #endregion

        //if(0==1)
        //{
        #region AnalyticalPrescriptions
        //objWriter.WriteStartElement("AnalyticalPrescriptions", null);	

        string appID = "";
        int j = 1;
        k = 1;
        if (ds_Spz_AnalitycalReport.Tables.Count > 2 && ds_Spz_AnalitycalReport.Tables[2].Rows.Count > 0)
        {
            objWriter.WriteStartElement("AnalyticalPrescriptions", null);
            for (int i = 0; i < ds_Spz_AnalitycalReport.Tables[2].Rows.Count; i++)
            {

                if (appID != ds_Spz_AnalitycalReport.Tables[2].Rows[i]["appId"].ToString())
                {
                    if (appID != "")
                    {
						WriteCustomEndElement(objWriter);
                        j = 1;
                        k = 1;
                    }
                    #region AnalyticalPrescription
                    objWriter.WriteStartElement("AnalyticalPrescription", null);

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["AppID"].ToString() != "")
                        WriteAttributeString(objWriter, "AppID", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["AppID"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["stencilNo"].ToString() != "")
                        WriteAttributeString(objWriter, "stencilNo", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["stencilNo"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["personPID"].ToString() != "")
                        WriteAttributeString(objWriter, "personPID", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["personPID"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["patientInsuranceHouse"].ToString() != "")
                        WriteAttributeString(objWriter, "patientInsuranceHouse", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["patientInsuranceHouse"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["serialNo"].ToString() != "")
                        WriteAttributeString(objWriter, "serialNo", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["serialNo"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["serialCode"].ToString() != "")
                        WriteAttributeString(objWriter, "serialCode", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["serialCode"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["contractNo"].ToString() != "")
                        WriteAttributeString(objWriter, "contractNo", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["contractNo"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["prescriptionDate"].ToString() != "")
                        WriteAttributeString(objWriter, "prescriptionDate", Convert.ToDateTime(ds_Spz_AnalitycalReport.Tables[2].Rows[i]["prescriptionDate"]).ToString("yyyy-MM-dd"));

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["merNo"].ToString() != "")
                        WriteAttributeString(objWriter, "merNo", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["merNo"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["merDate"].ToString() != "")
                        WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(ds_Spz_AnalitycalReport.Tables[2].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["patientType"].ToString() != "")
                        WriteAttributeString(objWriter, "patientType", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["patientType"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["nhp"].ToString() != "")
                        WriteAttributeString(objWriter, "nhp", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["nhp"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["prescriptionType"].ToString() != "")
                        WriteAttributeString(objWriter, "prescriptionType", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["prescriptionType"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["noDaysTreatment"].ToString() != "")
                        WriteAttributeString(objWriter, "noDaysTreatment", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["noDaysTreatment"].ToString());

                    WriteAttributeString(objWriter, "no", "1");

                }

                objWriter.WriteStartElement("AnalyticalPrescDrug", null);

                WriteAttributeString(objWriter, "no", j.ToString());

                if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["drugCode"].ToString() != "")
                    WriteAttributeString(objWriter, "drugCode", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["drugCode"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["activeSubstance"].ToString() != "")
                    WriteAttributeString(objWriter, "activeSubstance", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["activeSubstance"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["concentration"].ToString() != "")
                    WriteAttributeString(objWriter, "concentration", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["concentration"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["diseaseCategory"].ToString() != "")
                    WriteAttributeString(objWriter, "diseaseCategory", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["diseaseCategory"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["diseaseCode"].ToString() != "")
                    WriteAttributeString(objWriter, "diseaseCode", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["diseaseCode"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["pharmaceuticalForm"].ToString() != "")
                    WriteAttributeString(objWriter, "pharmaceuticalForm", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["pharmaceuticalForm"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["dose"].ToString() != "")
                    WriteAttributeString(objWriter, "dose", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["dose"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["quantity"].ToString() != "")
                    WriteAttributeString(objWriter, "quantity", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["quantity"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["diagnosticType"].ToString() != "")
                    WriteAttributeString(objWriter, "diagnosticType", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["diagnosticType"].ToString());

				WriteCustomEndElement(objWriter);

                if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["testName"].ToString() != "")
                {
                    objWriter.WriteStartElement("AnalyticalPrescTest", null);

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["no"].ToString() != "")
                        WriteAttributeString(objWriter, "no", k.ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["testName"].ToString() != "")
                        WriteAttributeString(objWriter, "testName", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["testName"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["monthsNo"].ToString() != "")
                        WriteAttributeString(objWriter, "monthsNo", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["monthsNo"].ToString());

                    if (ds_Spz_AnalitycalReport.Tables[2].Rows[i]["patientType"].ToString() != "")
                        WriteAttributeString(objWriter, "patientType", ds_Spz_AnalitycalReport.Tables[2].Rows[i]["presctest_patientType"].ToString());

					WriteCustomEndElement(objWriter);
                    k++;
                }

                appID = ds_Spz_AnalitycalReport.Tables[1].Rows[i]["appId"].ToString();
                j++;



                    #endregion
            }
            //end AnalyticalPrescription
			WriteCustomEndElement(objWriter);
            //end AnalyticalPrescriptions
			WriteCustomEndElement(objWriter);
        }

        //end AnalyticalPrescriptions
		//WriteCustomEndElement(objWriter);
        #endregion

        #region AnalyticalMedicalDevices
        #endregion

        #region AnalyticalMedicalNotes
        //objWriter.WriteStartElement("AnalyticalMedicalNotes", null);	

        if (ds_Spz_AnalitycalReport.Tables.Count > 3 && ds_Spz_AnalitycalReport.Tables[3].Rows.Count > 0)
        {
            objWriter.WriteStartElement("AnalyticalMedicalNotes", null);
            for (int i = 0; i < ds_Spz_AnalitycalReport.Tables[3].Rows.Count; i++)
            {
                #region AnalyticalMedicalNote
                objWriter.WriteStartElement("AnalyticalMedicalNote", null);

                if (ds_Spz_AnalitycalReport.Tables[3].Rows[i]["AppID"].ToString() != "")
                    WriteAttributeString(objWriter, "AppID", ds_Spz_AnalitycalReport.Tables[3].Rows[i]["AppID"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[3].Rows[i]["stencilNo"].ToString() != "")
                    WriteAttributeString(objWriter, "stencilNo", ds_Spz_AnalitycalReport.Tables[3].Rows[i]["stencilNo"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[3].Rows[i]["personPID"].ToString() != "")
                    WriteAttributeString(objWriter, "personPID", ds_Spz_AnalitycalReport.Tables[3].Rows[i]["personPID"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[3].Rows[i]["patientInsuranceHouse"].ToString() != "")
                    WriteAttributeString(objWriter, "patientInsuranceHouse", ds_Spz_AnalitycalReport.Tables[3].Rows[i]["patientInsuranceHouse"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[3].Rows[i]["serialNo"].ToString() != "")
                    WriteAttributeString(objWriter, "serialNo", ds_Spz_AnalitycalReport.Tables[3].Rows[i]["serialNo"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[3].Rows[i]["serialCode"].ToString() != "")
                    WriteAttributeString(objWriter, "serialCode", ds_Spz_AnalitycalReport.Tables[3].Rows[i]["serialCode"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[3].Rows[i]["issueDate"].ToString() != "")
                    WriteAttributeString(objWriter, "issueDate", Convert.ToDateTime(ds_Spz_AnalitycalReport.Tables[3].Rows[i]["issueDate"]).ToString("yyyy-MM-dd"));

                if (ds_Spz_AnalitycalReport.Tables[3].Rows[i]["merNo"].ToString() != "")
                    WriteAttributeString(objWriter, "merNo", ds_Spz_AnalitycalReport.Tables[3].Rows[i]["merNo"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[3].Rows[i]["merDate"].ToString() != "")
                    WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(ds_Spz_AnalitycalReport.Tables[3].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));

                if (ds_Spz_AnalitycalReport.Tables[3].Rows[i]["ticketType"].ToString() != "")
                    WriteAttributeString(objWriter, "ticketType", ds_Spz_AnalitycalReport.Tables[3].Rows[i]["ticketType"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[3].Rows[i]["no"].ToString() != "")
                    WriteAttributeString(objWriter, "no", "1");

                if (ds_Spz_AnalitycalReport.Tables[3].Rows[i]["diagnostic"].ToString() != "")
                    WriteAttributeString(objWriter, "diagnostic", ds_Spz_AnalitycalReport.Tables[3].Rows[i]["diagnostic"].ToString());

                if (ds_Spz_AnalitycalReport.Tables[3].Rows[i]["specialty"].ToString() != "")
                    WriteAttributeString(objWriter, "specialty", ds_Spz_AnalitycalReport.Tables[3].Rows[i]["specialty"].ToString());

                //end AnalyticalMedicalNote 
				WriteCustomEndElement(objWriter);
                #endregion
            }
            //end AnalyticalMedicalNotes
			WriteCustomEndElement(objWriter);
        }
        else
        {
            //objWriter.WriteStartElement("AnalyticalMedicalNote", null);
			//WriteCustomEndElement(objWriter);
        }

        //end AnalyticalMedicalNotes
		//WriteCustomEndElement(objWriter);
        #endregion

        //end report
		WriteCustomEndElement(objWriter);
    }

	private void DoExportSIUI_5(DataSet ds_SIUI_Paraclinic, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;
        objWriter.WriteStartElement("report");
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        if (ds_SIUI_Paraclinic.Tables.Count > 0 && ds_SIUI_Paraclinic.Tables[0].Rows.Count > 0)
        {

            WriteAttributeString(objWriter, "AppID", ds_SIUI_Paraclinic.Tables[0].Rows[0]["appId"].ToString());
            WriteAttributeString(objWriter, "laboratories", ds_SIUI_Paraclinic.Tables[0].Rows[0]["laboratories"].ToString());
            WriteAttributeString(objWriter, "fiscalCode", ds_SIUI_Paraclinic.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "contractNo", ds_SIUI_Paraclinic.Tables[0].Rows[0]["contractNo"].ToString());
            WriteAttributeString(objWriter, "insuranceHouse", ds_SIUI_Paraclinic.Tables[0].Rows[0]["insuranceHouse"].ToString());

            WriteAttributeString(objWriter, "totalRadiologyValue", ds_SIUI_Paraclinic.Tables[0].Rows[0]["totalRadiologyValue"].ToString());
            WriteAttributeString(objWriter, "totalAnalysisValue", ds_SIUI_Paraclinic.Tables[0].Rows[0]["totalAnalysisValue"].ToString());
            WriteAttributeString(objWriter, "totalExplorationValue", ds_SIUI_Paraclinic.Tables[0].Rows[0]["totalExplorationValue"].ToString());
        }
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(parameters.startDate).ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(parameters.endDate).ToString("yyyy-MM-dd"));

        #region services
        objWriter.WriteStartElement("services", null);

        if (ds_SIUI_Paraclinic.Tables.Count > 1 && ds_SIUI_Paraclinic.Tables[1].Rows.Count > 0)
        {
            for (int i = 0; i < ds_SIUI_Paraclinic.Tables[1].Rows.Count; i++)
            {
                objWriter.WriteStartElement("service", null);

                WriteAttributeString(objWriter, "AppID", ds_SIUI_Paraclinic.Tables[1].Rows[i]["appId"].ToString());
                WriteAttributeString(objWriter, "stencilNo", ds_SIUI_Paraclinic.Tables[1].Rows[i]["stencilNo"].ToString());
                WriteAttributeString(objWriter, "personPID", ds_SIUI_Paraclinic.Tables[1].Rows[i]["personPID"].ToString());
                //WriteAttributeString(objWriter, "patientInsuranceHouse", ds_SIUI_Paraclinic.Tables[1].Rows[i]["patientInsuranceHouse"].ToString());
                WriteAttributeString(objWriter, "reportedService", ds_SIUI_Paraclinic.Tables[1].Rows[i]["reportedService"].ToString());
                WriteAttributeString(objWriter, "medSrvPack", ds_SIUI_Paraclinic.Tables[1].Rows[i]["medSrvPack"].ToString());
                WriteAttributeString(objWriter, "quantity", ds_SIUI_Paraclinic.Tables[1].Rows[i]["quantity"].ToString());
                WriteAttributeString(objWriter, "merNo", ds_SIUI_Paraclinic.Tables[1].Rows[i]["merNo"].ToString());
                WriteAttributeString(objWriter, "serviceDate", Convert.ToDateTime(ds_SIUI_Paraclinic.Tables[1].Rows[i]["serviceDate"]).ToString("yyyy-MM-dd"));
                //WriteAttributeString(objWriter, "reportedTarrif", ds.Tables[1].Rows[i]["reportedTarrif"].ToString());
                WriteAttributeString(objWriter, "refferedByStencilNo", ds_SIUI_Paraclinic.Tables[1].Rows[i]["refferedByStencilNo"].ToString());
                WriteAttributeString(objWriter, "refferedBySerialNo", ds_SIUI_Paraclinic.Tables[1].Rows[i]["refferedBySerialNo"].ToString());
                WriteAttributeString(objWriter, "refferedBySerialCode", ds_SIUI_Paraclinic.Tables[1].Rows[i]["refferedBySerialCode"].ToString());
                //WriteAttributeString(objWriter, "refferedBySpecialty", ds_SIUI_Paraclinic.Tables[1].Rows[i]["refferedBySpecialty"].ToString());
                WriteAttributeString(objWriter, "refferedByDiagnostic", ds_SIUI_Paraclinic.Tables[1].Rows[i]["refferedByDiagnostic"].ToString());
                WriteAttributeString(objWriter, "refferedByContractNo", ds_SIUI_Paraclinic.Tables[1].Rows[i]["refferedByContractNo"].ToString());
                WriteAttributeString(objWriter, "refferedByDate", Convert.ToDateTime(ds_SIUI_Paraclinic.Tables[1].Rows[i]["refferedByDate"]).ToString("yyyy-MM-dd"));
                if (ds_SIUI_Paraclinic.Tables[1].Rows[i]["cockroftGaultFormula"].ToString() != "")
                    WriteAttributeString(objWriter, "cockroftGaultFormula", ds_SIUI_Paraclinic.Tables[1].Rows[i]["cockroftGaultFormula"].ToString());
                WriteAttributeString(objWriter, "patientSource", ds_SIUI_Paraclinic.Tables[1].Rows[i]["patientSource"].ToString());
                //WriteAttributeString(objWriter, "onDemand", ds_SIUI_Paraclinic.Tables[1].Rows[i]["onDemand"].ToString());
                //WriteAttributeString(objWriter, "emergency", ds_SIUI_Paraclinic.Tables[1].Rows[i]["emergency"].ToString());
                WriteAttributeString(objWriter, "lastOption", ds_SIUI_Paraclinic.Tables[1].Rows[i]["lastOption"].ToString());
                WriteAttributeString(objWriter, "refferedByPC", ds_SIUI_Paraclinic.Tables[1].Rows[i]["refferedByPC"].ToString());
                WriteAttributeString(objWriter, "personType", ds_SIUI_Paraclinic.Tables[1].Rows[i]["personType"].ToString());
				WriteCustomEndElement(objWriter);


                //end Service

            }
            //end services
			WriteCustomEndElement(objWriter);
        }
        else
        {
            objWriter.WriteStartElement("service", null);
			WriteCustomEndElement(objWriter);
        }
        #endregion
        //end report
		WriteCustomEndElement(objWriter);
    }

	private void DoExportSIUI_6(DataSet ds_SIUI_Dializa, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;
        string[] arrHDDate = new string[10000];
        string[] arrDPDate = new string[10000];

        #region report
        
        objWriter.WriteStartElement("report");
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(parameters.startDate).ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(parameters.endDate).ToString("yyyy-MM-dd"));
        if (ds_SIUI_Dializa.Tables.Count > 0 && ds_SIUI_Dializa.Tables[0].Rows.Count > 0)
        {

            WriteAttributeString(objWriter, "provider", ds_SIUI_Dializa.Tables[0].Rows[0]["provider"].ToString());
            WriteAttributeString(objWriter, "fiscalCode", ds_SIUI_Dializa.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "insuranceHouse", ds_SIUI_Dializa.Tables[0].Rows[0]["insuranceHouse"].ToString());
            WriteAttributeString(objWriter, "supervisorStencilNo", ds_SIUI_Dializa.Tables[0].Rows[0]["parafa"].ToString());
            WriteAttributeString(objWriter, "AppID", ds_SIUI_Dializa.Tables[0].Rows[0]["appId"].ToString());
            WriteAttributeString(objWriter, "contractNo", ds_SIUI_Dializa.Tables[0].Rows[0]["contractNo"].ToString());
        }

        #endregion

        #region HDs
        objWriter.WriteStartElement("HDs", null);

        if (ds_SIUI_Dializa.Tables.Count > 1 && ds_SIUI_Dializa.Tables[1].Rows.Count > 0)
        {
            string appInternID = "";
            string pid = "", noHospitalFileDay = "", sessionCharge = "";
            string validFrom = "", validTo = "", obs = "", temporaryTransfer = "", AppID = "", personType = "";
            int k = 1;
            for (int i = 0; i < ds_SIUI_Dializa.Tables[1].Rows.Count; i++)
            {
                if (appInternID != ds_SIUI_Dializa.Tables[1].Rows[i]["AppID"].ToString())
                {
                    if (appInternID != "")
                    {
                        #region HDDate
                        if (k > 1)
                        {
                            objWriter.WriteStartElement("HD", null);
                            WriteAttributeString(objWriter, "pid", pid);
                            WriteAttributeString(objWriter, "noHospitalFileDay", noHospitalFileDay);
                            WriteAttributeString(objWriter, "noReportedHemSession", Convert.ToString(k - 1));
                            WriteAttributeString(objWriter, "sessionCharge", sessionCharge);
                            WriteAttributeString(objWriter, "reportedRefoundSumE", Convert.ToString((k - 1) * Convert.ToDecimal(sessionCharge)));
                            if (validFrom != "")
                                WriteAttributeString(objWriter, "validFrom", validFrom);
                            if (validTo != "")
                                WriteAttributeString(objWriter, "validTo", validTo);
                            WriteAttributeString(objWriter, "obs", obs);
                            WriteAttributeString(objWriter, "temporaryTransfer", temporaryTransfer);
                            WriteAttributeString(objWriter, "AppID", AppID);
                            WriteAttributeString(objWriter, "personType", personType);

                            for (int t = 1; t < k; t++)
                            {
                                objWriter.WriteStartElement("HDDate", null);
                                WriteAttributeString(objWriter, "date", arrHDDate[t].ToString());
								WriteCustomEndElement(objWriter);
                            }
                            k = 1;
                            Array.Clear(arrHDDate, 0, arrHDDate.Length);

							WriteCustomEndElement(objWriter);
                            objWriter.Flush();
                        }
                        #endregion

                    }

                    #region HD

                    pid = ds_SIUI_Dializa.Tables[1].Rows[i]["pid"].ToString();
                    noHospitalFileDay = ds_SIUI_Dializa.Tables[1].Rows[i]["noHospitalFileDay"].ToString();
                    sessionCharge = ds_SIUI_Dializa.Tables[1].Rows[i]["sessionCharge"].ToString();
                    if (ds_SIUI_Dializa.Tables[1].Rows[i]["HDDate"].ToString() != "")
                        validFrom = Convert.ToDateTime(ds_SIUI_Dializa.Tables[1].Rows[i]["HDDate"]).ToString("yyyy-MM-dd");
                    if (ds_SIUI_Dializa.Tables[1].Rows[i]["HDDate"].ToString() != "")
                        validTo = Convert.ToDateTime(ds_SIUI_Dializa.Tables[1].Rows[i]["HDDate"]).ToString("yyyy-MM-dd");

                    obs = ds_SIUI_Dializa.Tables[1].Rows[i]["obs"].ToString();
                    temporaryTransfer = ds_SIUI_Dializa.Tables[1].Rows[i]["temporaryTransfer"].ToString();
                    AppID = ds_SIUI_Dializa.Tables[1].Rows[i]["AppID"].ToString();
                    personType = ds_SIUI_Dializa.Tables[1].Rows[i]["personType"].ToString();


                }
                if (ds_SIUI_Dializa.Tables[1].Rows[i]["HDDate"].ToString() != "")
                {
                    arrHDDate[k] = Convert.ToDateTime(ds_SIUI_Dializa.Tables[1].Rows[i]["HDDate"]).ToString("yyyy-MM-dd");
                    k++;
                }
                if (ds_SIUI_Dializa.Tables[1].Rows[i]["HDDate"].ToString() != "")
                    validTo = Convert.ToDateTime(ds_SIUI_Dializa.Tables[1].Rows[i]["HDDate"]).ToString("yyyy-MM-dd");


                appInternID = ds_SIUI_Dializa.Tables[1].Rows[i]["AppID"].ToString();

                //end HD

                    #endregion
            }
        }
        else
        {
            objWriter.WriteStartElement("HD", null);
            objWriter.WriteStartElement("HDDate", null);
			WriteCustomEndElement(objWriter);
			WriteCustomEndElement(objWriter);
        }

        //end HDs
		WriteCustomEndElement(objWriter);
        objWriter.Flush();
        #endregion

        #region DPs
        objWriter.WriteStartElement("DPs", null);

        if (ds_SIUI_Dializa.Tables.Count > 2 && ds_SIUI_Dializa.Tables[2].Rows.Count > 0)
        {
            string appInternID = "";
            string pid = "", noHospitalFileDay = "", sessionCharge = "";
            string validFrom = "", validTo = "", obs = "", temporaryTransfer = "", AppID = "", personType = "";
            int k = 1;
            for (int i = 0; i < ds_SIUI_Dializa.Tables[2].Rows.Count; i++)
            {
                if (appInternID != ds_SIUI_Dializa.Tables[2].Rows[i]["AppID"].ToString())
                {
                    if (appInternID != "")
                    {
                        #region DPDate
                        if (k > 1)
                        {
                            objWriter.WriteStartElement("DP", null);
                            WriteAttributeString(objWriter, "pid", pid);
                            WriteAttributeString(objWriter, "noHospitalFileDay", noHospitalFileDay);
                            //WriteAttributeString(objWriter, "noReportedHemSession", Convert.ToString(k-1));
                            //WriteAttributeString(objWriter, "sessionCharge", sessionCharge);
                            WriteAttributeString(objWriter, "reportedRefoundSumE", Convert.ToString((k - 1) * Convert.ToDecimal(sessionCharge)));

                            if (validFrom != "")
                                WriteAttributeString(objWriter, "validFrom", validFrom);

                            if (validTo != "")
                                WriteAttributeString(objWriter, "validTo", validTo);
                            WriteAttributeString(objWriter, "obs", obs);
                            //WriteAttributeString(objWriter, "temporaryTransfer", temporaryTransfer);
                            WriteAttributeString(objWriter, "AppID", AppID);
                            WriteAttributeString(objWriter, "personType", personType);

                            for (int t = 1; t < k; t++)
                                //{
                                //	objWriter.WriteStartElement("DPDate", null);
                                //	WriteAttributeString(objWriter, "date", arrDPDate[t].ToString()) ;
								//	WriteCustomEndElement(objWriter);
                                //}
                                k = 1;
                            Array.Clear(arrDPDate, 0, arrDPDate.Length);

							WriteCustomEndElement(objWriter);
                            objWriter.Flush();
                        }
                        #endregion

                    }
                    #region DP

                    pid = ds_SIUI_Dializa.Tables[2].Rows[i]["pid"].ToString();

                    noHospitalFileDay = ds_SIUI_Dializa.Tables[2].Rows[i]["noHospitalFileDay"].ToString();

                    sessionCharge = ds_SIUI_Dializa.Tables[2].Rows[i]["sessionCharge"].ToString();

                    if (ds_SIUI_Dializa.Tables[2].Rows[i]["DPDate"].ToString() != "")
                        validFrom = Convert.ToDateTime(ds_SIUI_Dializa.Tables[2].Rows[i]["DPDate"]).ToString("yyyy-MM-dd");

                    if (ds_SIUI_Dializa.Tables[2].Rows[i]["DPDate"].ToString() != "")
                        validTo = Convert.ToDateTime(ds_SIUI_Dializa.Tables[2].Rows[i]["DPDate"]).ToString("yyyy-MM-dd");

                    obs = ds_SIUI_Dializa.Tables[2].Rows[i]["obs"].ToString();

                    temporaryTransfer = ds_SIUI_Dializa.Tables[2].Rows[i]["temporaryTransfer"].ToString();

                    AppID = ds_SIUI_Dializa.Tables[2].Rows[i]["AppID"].ToString();

                    personType = ds_SIUI_Dializa.Tables[2].Rows[i]["personType"].ToString();


                }
                if (ds_SIUI_Dializa.Tables[2].Rows[i]["DPDate"].ToString() != "")
                {
                    arrDPDate[k] = Convert.ToDateTime(ds_SIUI_Dializa.Tables[2].Rows[i]["DPDate"]).ToString("yyyy-MM-dd");
                    k++;
                }
                if (ds_SIUI_Dializa.Tables[2].Rows[i]["DPDate"].ToString() != "")
                    //throw new Exception(GetErrorMessage(ds.Tables[2].Rows[i]["DPDate"].ToString()));
                    validTo = Convert.ToDateTime(ds_SIUI_Dializa.Tables[2].Rows[i]["DPDate"]).ToString("yyyy-MM-dd");


                appInternID = ds_SIUI_Dializa.Tables[2].Rows[i]["AppID"].ToString();

                //end DP

                    #endregion
            }
        }
        else
        {
            objWriter.WriteStartElement("DP", null);
            objWriter.WriteStartElement("ForeignPerson", null);
			WriteCustomEndElement(objWriter);
			WriteCustomEndElement(objWriter);
        }
        //end DPs
		WriteCustomEndElement(objWriter);
        objWriter.Flush();
        #endregion
		WriteCustomEndElement(objWriter);
    }

	private void DoExportSIUI_7(DataSet ds_SIUI_Spital_DRG_Cronici, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;

		#region opening of report tag
		objWriter.WriteStartElement("report");
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "startFrom", parameters.StartDate.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "endTo", parameters.EndDate.ToString("yyyy-MM-dd"));
        if (ds_SIUI_Spital_DRG_Cronici.Tables.Count > 0 && ds_SIUI_Spital_DRG_Cronici.Tables[0].Rows.Count > 0)
        {
            WriteAttributeString(objWriter, "hospitalCode", ds_SIUI_Spital_DRG_Cronici.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "fiscalCode", ds_SIUI_Spital_DRG_Cronici.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "insuranceHouse", ds_SIUI_Spital_DRG_Cronici.Tables[0].Rows[0]["insuranceHouse"].ToString());
            WriteAttributeString(objWriter, "contractNo", ds_SIUI_Spital_DRG_Cronici.Tables[0].Rows[0]["contractNo"].ToString());
            WriteAttributeString(objWriter, "AppID", ds_SIUI_Spital_DRG_Cronici.Tables[0].Rows[0]["appId"].ToString());
		}
		#endregion

		#region Chronics

		objWriter.WriteStartElement("Chronics", null);
        if (ds_SIUI_Spital_DRG_Cronici.Tables.Count > 5 && ds_SIUI_Spital_DRG_Cronici.Tables[5].Rows.Count > 0)
        {
            for (int i = 0; i < ds_SIUI_Spital_DRG_Cronici.Tables[5].Rows.Count; i++)
            {
                #region Chronic
                objWriter.WriteStartElement("Chronic", null);
                WriteAttributeString(objWriter, "AppID", Convert.ToString((i + 1)));
                WriteAttributeString(objWriter, "hospitalDeptCode", ds_SIUI_Spital_DRG_Cronici.Tables[5].Rows[i]["hospitalDeptCode"].ToString());
                WriteAttributeString(objWriter, "realisedCasesNo", ds_SIUI_Spital_DRG_Cronici.Tables[5].Rows[i]["realisedCasesNo"].ToString());
                WriteAttributeString(objWriter, "invalidatedCasesNo", ds_SIUI_Spital_DRG_Cronici.Tables[5].Rows[i]["invalidatedCasesNo"].ToString());

                if (ds_SIUI_Spital_DRG_Cronici.Tables[5].Rows[i]["optimalDuration"].ToString() != "")
                    WriteAttributeString(objWriter, "optimalDuration", ds_SIUI_Spital_DRG_Cronici.Tables[5].Rows[i]["optimalDuration"].ToString());
                WriteAttributeString(objWriter, "personType", ds_SIUI_Spital_DRG_Cronici.Tables[5].Rows[i]["personType"].ToString());


                //end Chronic 
				WriteCustomEndElement(objWriter);

                #endregion
            }
        }
		WriteCustomEndElement(objWriter);
        #endregion

        #region ChronicPrescriptions

        string appID = "";
        int j = 1;
        if (ds_SIUI_Spital_DRG_Cronici.Tables.Count > 1 && ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows.Count > 0)
        {
            objWriter.WriteStartElement("ChronicPrescriptions", null);
            for (int i = 0; i < ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows.Count; i++)
            {

                if (appID != ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["appId"].ToString())
                {
                    if (appID != "")
                    {
						WriteCustomEndElement(objWriter);
                        j = 1;
                    }
                    #region ChronicPrescription
                    objWriter.WriteStartElement("ChronicPrescription", null);

                    WriteAttributeString(objWriter, "AppID", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["appId"].ToString());
                    WriteAttributeString(objWriter, "stencilNo", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["stencilNo"].ToString());
                    WriteAttributeString(objWriter, "personPID", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["personPID"].ToString());
                    WriteAttributeString(objWriter, "patientInsuranceHouse", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["patientInsuranceHouse"].ToString());
                    WriteAttributeString(objWriter, "serialNo", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["serialNo"].ToString());
                    WriteAttributeString(objWriter, "serialCode", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["serialCode"].ToString());
                    WriteAttributeString(objWriter, "contractNo", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["contractNo"].ToString());
                    WriteAttributeString(objWriter, "prescriptionDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["prescriptionDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "merNo", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["merNo"].ToString());
                    WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));
                    //WriteAttributeString(objWriter, "no", "");
                    //WriteAttributeString(objWriter, "nhp", "");
                    WriteAttributeString(objWriter, "patientType", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["patientType"].ToString());
                    WriteAttributeString(objWriter, "prescriptionType", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["prescriptionType"].ToString());
                    WriteAttributeString(objWriter, "noDaysTreatment", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["noDaysTreatment"].ToString());
                    #endregion

                }
                #region ChronicMedicalDevices
                objWriter.WriteStartElement("ChronicPrescDrug", null);

                WriteAttributeString(objWriter, "no", j.ToString());
                WriteAttributeString(objWriter, "drugCode", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["drugCode"].ToString());
                WriteAttributeString(objWriter, "activeSubstance", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["activeSubstance"].ToString());
                WriteAttributeString(objWriter, "concentration", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["concentration"].ToString());
                WriteAttributeString(objWriter, "diseaseCode", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["diseaseCode"].ToString());
                if (ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["diseaseCategory"].ToString() != "")
                    WriteAttributeString(objWriter, "diseaseCategory", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["diseaseCategory"].ToString());
                WriteAttributeString(objWriter, "pharmaceuticalForm", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["pharmaceuticalForm"].ToString());
                WriteAttributeString(objWriter, "quantity", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["quantity"].ToString());
                WriteAttributeString(objWriter, "diagnosticType", ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["diagnosticType"].ToString());

				WriteCustomEndElement(objWriter);

                appID = ds_SIUI_Spital_DRG_Cronici.Tables[1].Rows[i]["appId"].ToString();
                j++;
                #endregion
            }
            //end ChronicMedicalDevice
			WriteCustomEndElement(objWriter);
            //end ChronicMedicalDevices
			WriteCustomEndElement(objWriter);
        }

        #endregion

        #region ChronicMedicalNotes

        if (ds_SIUI_Spital_DRG_Cronici.Tables.Count > 2 && ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows.Count > 0)
        {
            objWriter.WriteStartElement("ChronicMedicalNotes", null);
            for (int i = 0; i < ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows.Count; i++)
            {
                #region ChronicMedicalNote
                objWriter.WriteStartElement("ChronicMedicalNote ", null);
                WriteAttributeString(objWriter, "AppID", ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows[i]["appId"].ToString());
                WriteAttributeString(objWriter, "stencilNo", ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows[i]["stencilNo"].ToString());
                WriteAttributeString(objWriter, "personPID", ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows[i]["personPID"].ToString());
                WriteAttributeString(objWriter, "patientInsuranceHouse", ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows[i]["patientInsuranceHouse"].ToString());
                WriteAttributeString(objWriter, "serialNo", ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows[i]["serialNo"].ToString());
                WriteAttributeString(objWriter, "serialCode", ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows[i]["serialCode"].ToString());
                WriteAttributeString(objWriter, "issueDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows[i]["issueDate"]).ToString("yyyy-MM-dd"));
                WriteAttributeString(objWriter, "merNo", ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows[i]["merNo"].ToString());
                WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));
                WriteAttributeString(objWriter, "ticketType", ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows[i]["ticketType"].ToString());
                WriteAttributeString(objWriter, "no", ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows[i]["appId"].ToString());
                WriteAttributeString(objWriter, "diagnostic", ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows[i]["diagnostic"].ToString());
                WriteAttributeString(objWriter, "specialty", ds_SIUI_Spital_DRG_Cronici.Tables[2].Rows[i]["specialty"].ToString());


                //end ChronicMedicalNote
				WriteCustomEndElement(objWriter);
                #endregion
            }
            //end ChronicMedicalNotes
			WriteCustomEndElement(objWriter);
        }

        #endregion

        #region ForeignPersons

        string personIdentifier = "";
        int j2 = 1;
        if (ds_SIUI_Spital_DRG_Cronici.Tables.Count > 3 && ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows.Count > 0)
        {
            objWriter.WriteStartElement("ForeignPersons", null);
            for (int i = 0; i < ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows.Count; i++)
            {

                if (personIdentifier != ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["personIdentifier"].ToString())
                {
                    if (personIdentifier != "")
                    {
						WriteCustomEndElement(objWriter);
                        j2 = 1;
                    }

                    #region ForeignPerson
                    objWriter.WriteStartElement("ForeignPerson", null);


                    WriteAttributeString(objWriter, "personIdentifier", ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["personIdentifier"].ToString());
                    WriteAttributeString(objWriter, "personFirstName", ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["personFirstName"].ToString());
                    WriteAttributeString(objWriter, "personLastName", ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["personLastName"].ToString());
                    WriteAttributeString(objWriter, "birthDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["birthDate"]).ToString("yyyy-MM-dd"));

                    if (ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["countryCode"].ToString() != "")
                        WriteAttributeString(objWriter, "countryCode", ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["countryCode"].ToString());

                    if (ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["cardCode"].ToString() != "")
                        WriteAttributeString(objWriter, "cardCode", ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["personIdentifier"].ToString());

                    if (ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["cardExpireDate"].ToString() != "")
                        WriteAttributeString(objWriter, "cardExpireDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["cardExpireDate"]).ToString("yyyy-MM-dd"));

                    WriteAttributeString(objWriter, "caseId", ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["caseId"].ToString());
                    WriteAttributeString(objWriter, "personType", ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["personType"].ToString());
                    WriteAttributeString(objWriter, "internmentDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["internmentDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "releaseDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["releaseDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "hospitalDeptCode", ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["hospitalDeptCode"].ToString());
                }
                objWriter.WriteStartElement("ForeignProcedure", null);

                WriteAttributeString(objWriter, "procedureCode", ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["procedureCode"].ToString());

				WriteCustomEndElement(objWriter);

                personIdentifier = ds_SIUI_Spital_DRG_Cronici.Tables[3].Rows[i]["personIdentifier"].ToString();
                j2++;

                    #endregion
            }
            //end ForeignPerson 
			WriteCustomEndElement(objWriter);
            //end ForeignPersons
			WriteCustomEndElement(objWriter);
        }

        #endregion

        #region PidLists

        objWriter.WriteStartElement("PidLists", null);
        string sheetNo = "";
        int j3 = 1;
        if (ds_SIUI_Spital_DRG_Cronici.Tables.Count > 4 && ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows.Count > 0)
        {

            for (int i = 0; i < ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows.Count; i++)
            {
                if (sheetNo != ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["sheetNo"].ToString())
                {
                    if (sheetNo != "")
                    {
						WriteCustomEndElement(objWriter);
                        j3 = 1;
                    }
                    #region PidList
                    objWriter.WriteStartElement("PidList", null);


                    WriteAttributeString(objWriter, "AppID", ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["AppID"].ToString());
                    WriteAttributeString(objWriter, "pid", ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["pid"].ToString());
                    WriteAttributeString(objWriter, "birthDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["birthDate"]).ToString("yyyy-MM-dd"));
                    //WriteAttributeString(objWriter, "specialSituationCode", ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["specialSituationCode"].ToString());

                    if (ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["specialSituationCode"].ToString() != "")
                        WriteAttributeString(objWriter, "specialSituationCode", ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["specialSituationCode"].ToString());

                    WriteAttributeString(objWriter, "internmentDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["internmentDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "hospitalDeptCode", ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["hospitalDeptCode"].ToString());

                    if (ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["releaseDate"].ToString() != "")
                        WriteAttributeString(objWriter, "releaseDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["releaseDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "sheetNo", ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["sheetNo"].ToString());

                    if (ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["case_id"].ToString() != "")
                        WriteAttributeString(objWriter, "case_id", ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["case_id"].ToString());

                    WriteAttributeString(objWriter, "internmentCriteriaCode", ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["internmentCriteriaCode"].ToString());
                    #endregion
                }
                #region Procedure
                if (ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["procedureCode"].ToString() != "")
                {
                    objWriter.WriteStartElement("Procedure", null);
                    WriteAttributeString(objWriter, "procedureCode", ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["procedureCode"].ToString());
					WriteCustomEndElement(objWriter);
                }
                #endregion
                sheetNo = ds_SIUI_Spital_DRG_Cronici.Tables[4].Rows[i]["sheetNo"].ToString();
                j3++;
            }
			WriteCustomEndElement(objWriter);
        }
		WriteCustomEndElement(objWriter);

        #endregion

        #region OtherSuppliers

        objWriter.WriteStartElement("OtherSuppliers", null);
        string sheetNo2 = "";
        int j4 = 1;
        if (ds_SIUI_Spital_DRG_Cronici.Tables.Count > 6 && ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows.Count > 0)
        {

            for (int i = 0; i < ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows.Count; i++)
            {
                if (sheetNo2 != ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["sheetNo"].ToString())
                {
                    if (sheetNo2 != "")
                    {
						WriteCustomEndElement(objWriter);
                        j4 = 1;
                    }
                    #region OtherSupplier
                    objWriter.WriteStartElement("OtherSupplier", null);


                    WriteAttributeString(objWriter, "AppID", ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["AppID"].ToString());
                    if (ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["personIdentifier"].ToString() != "")
                        WriteAttributeString(objWriter, "personIdentifier", ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["personIdentifier"].ToString());
                    WriteAttributeString(objWriter, "serviceCode", ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["serviceCode"].ToString());
                    WriteAttributeString(objWriter, "noServices", ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["noServices"].ToString());
                    WriteAttributeString(objWriter, "tariff", ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["tariff"].ToString());
                    WriteAttributeString(objWriter, "servicesData", Convert.ToDateTime(ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["servicesData"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "supplierCode", ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["supplierCode"].ToString());
                    WriteAttributeString(objWriter, "supplierContractNo", ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["supplierContractNo"].ToString());
                    WriteAttributeString(objWriter, "serviceType", ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["serviceType"].ToString());
                    WriteAttributeString(objWriter, "supplierOrgUnit", ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["supplierOrgUnit"].ToString());
                    WriteAttributeString(objWriter, "sheetNo", ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["sheetNo"].ToString());


                    #endregion
                }
                sheetNo2 = ds_SIUI_Spital_DRG_Cronici.Tables[6].Rows[i]["sheetNo"].ToString();
                j4++;
            }
			WriteCustomEndElement(objWriter);

        }

		WriteCustomEndElement(objWriter);

        #endregion

        //closing the report tag
		WriteCustomEndElement(objWriter);
    }

	private void DoExportSIUI_8(DataSet ds_SIUI_Spital_DRG_Acuti, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;
        objWriter.WriteStartElement("report");
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(parameters.startDate).ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(parameters.endDate).ToString("yyyy-MM-dd"));
        if (ds_SIUI_Spital_DRG_Acuti.Tables.Count > 0 && ds_SIUI_Spital_DRG_Acuti.Tables[0].Rows.Count > 0)
        {
            WriteAttributeString(objWriter, "hospitalCode", ds_SIUI_Spital_DRG_Acuti.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "fiscalCode", ds_SIUI_Spital_DRG_Acuti.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "insuranceHouse", ds_SIUI_Spital_DRG_Acuti.Tables[0].Rows[0]["insuranceHouse"].ToString());
            WriteAttributeString(objWriter, "contractNo", ds_SIUI_Spital_DRG_Acuti.Tables[0].Rows[0]["contractNo"].ToString());
            WriteAttributeString(objWriter, "AppID", ds_SIUI_Spital_DRG_Acuti.Tables[0].Rows[0]["appId"].ToString());
        }

        #region Acute

        if (ds_SIUI_Spital_DRG_Acuti.Tables.Count > 5 && ds_SIUI_Spital_DRG_Acuti.Tables[5].Rows.Count > 0)
        {
            objWriter.WriteStartElement("Acute", null);
            for (int i = 0; i < ds_SIUI_Spital_DRG_Acuti.Tables[5].Rows.Count; i++)
            {
                #region Acut
                objWriter.WriteStartElement("Acut", null);
                WriteAttributeString(objWriter, "AppID", Convert.ToString((i + 1)));
                WriteAttributeString(objWriter, "hospitalDeptCode", ds_SIUI_Spital_DRG_Acuti.Tables[5].Rows[i]["hospitalDeptCode"].ToString());
                WriteAttributeString(objWriter, "realisedCasesNo", ds_SIUI_Spital_DRG_Acuti.Tables[5].Rows[i]["realisedCasesNo"].ToString());
                WriteAttributeString(objWriter, "personType", ds_SIUI_Spital_DRG_Acuti.Tables[5].Rows[i]["personType"].ToString());
                //end Acut 
				WriteCustomEndElement(objWriter);

                #endregion
            }
            //end Acute
			WriteCustomEndElement(objWriter);
        }

        #endregion

        #region AcutPrescriptions

        string appID = "";
        int j = 1;
        if (ds_SIUI_Spital_DRG_Acuti.Tables.Count > 1 && ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows.Count > 0)
        {
            objWriter.WriteStartElement("AcutPrescriptions", null);
            for (int i = 0; i < ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows.Count; i++)
            {

                if (appID != ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["appId"].ToString())
                {
                    if (appID != "")
                    {
						WriteCustomEndElement(objWriter);
                        j = 1;
                    }
                    #region AcutPrescription
                    objWriter.WriteStartElement("AcutPrescription", null);

                    WriteAttributeString(objWriter, "AppID", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["appId"].ToString());
                    WriteAttributeString(objWriter, "stencilNo", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["stencilNo"].ToString());
                    WriteAttributeString(objWriter, "personPID", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["personPID"].ToString());
                    WriteAttributeString(objWriter, "patientInsuranceHouse", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["patientInsuranceHouse"].ToString());
                    WriteAttributeString(objWriter, "serialNo", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["serialNo"].ToString());
                    WriteAttributeString(objWriter, "serialCode", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["serialCode"].ToString());
                    WriteAttributeString(objWriter, "contractNo", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["contractNo"].ToString());
                    WriteAttributeString(objWriter, "prescriptionDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["prescriptionDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "merNo", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["merNo"].ToString());
                    WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "patientType", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["patientType"].ToString());
                    WriteAttributeString(objWriter, "prescriptionType", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["prescriptionType"].ToString());
                    WriteAttributeString(objWriter, "noDaysTreatment", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["noDaysTreatment"].ToString());
                    #endregion

                }
                #region AcutPrescDrug
                objWriter.WriteStartElement("AcutPrescDrug", null);

                WriteAttributeString(objWriter, "no", j.ToString());
                WriteAttributeString(objWriter, "drugCode", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["drugCode"].ToString());
                WriteAttributeString(objWriter, "activeSubstance", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["activeSubstance"].ToString());
                WriteAttributeString(objWriter, "concentration", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["concentration"].ToString());
                WriteAttributeString(objWriter, "diseaseCode", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["diseaseCode"].ToString());
                if (ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["diseaseCategory"].ToString() != "")
                    WriteAttributeString(objWriter, "diseaseCategory", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["diseaseCategory"].ToString());
                WriteAttributeString(objWriter, "pharmaceuticalForm", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["pharmaceuticalForm"].ToString());
                WriteAttributeString(objWriter, "quantity", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["quantity"].ToString());
                WriteAttributeString(objWriter, "diagnosticType", ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["diagnosticType"].ToString());

				WriteCustomEndElement(objWriter);

                appID = ds_SIUI_Spital_DRG_Acuti.Tables[1].Rows[i]["appId"].ToString();
                j++;
                #endregion
            }
            //end AcutPrescDrug
			WriteCustomEndElement(objWriter);
            //end AcutPrescDrug
			WriteCustomEndElement(objWriter);
        }

        #endregion

        #region AcutMedicalNotes

        if (ds_SIUI_Spital_DRG_Acuti.Tables.Count > 2 && ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows.Count > 0)
        {
            objWriter.WriteStartElement("AcutMedicalNotes", null);
            for (int i = 0; i < ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows.Count; i++)
            {
                #region AcutMedicalNote
                objWriter.WriteStartElement("AcutMedicalNote", null);

                WriteAttributeString(objWriter, "AppID", ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows[i]["appId"].ToString());
                WriteAttributeString(objWriter, "stencilNo", ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows[i]["stencilNo"].ToString());
                WriteAttributeString(objWriter, "personPID", ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows[i]["personPID"].ToString());
                WriteAttributeString(objWriter, "patientInsuranceHouse", ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows[i]["patientInsuranceHouse"].ToString());
                WriteAttributeString(objWriter, "serialNo", ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows[i]["serialNo"].ToString());
                WriteAttributeString(objWriter, "serialCode", ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows[i]["serialCode"].ToString());
                WriteAttributeString(objWriter, "issueDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows[i]["issueDate"]).ToString("yyyy-MM-dd"));
                WriteAttributeString(objWriter, "merNo", ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows[i]["merNo"].ToString());
                WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));
                WriteAttributeString(objWriter, "ticketType", ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows[i]["ticketType"].ToString());
                WriteAttributeString(objWriter, "no", ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows[i]["appId"].ToString());
                WriteAttributeString(objWriter, "diagnostic", ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows[i]["diagnostic"].ToString());
                WriteAttributeString(objWriter, "specialty", ds_SIUI_Spital_DRG_Acuti.Tables[2].Rows[i]["specialty"].ToString());


                //end AcutMedicalNote
				WriteCustomEndElement(objWriter);
                #endregion
            }
            //end AcutMedicalNotes
			WriteCustomEndElement(objWriter);
        }

        #endregion

        #region ForeignPersons

        string personIdentifier = "";
        int j2 = 1;
        if (ds_SIUI_Spital_DRG_Acuti.Tables.Count > 3 && ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows.Count > 0)
        {
            objWriter.WriteStartElement("ForeignPersons", null);
            for (int i = 0; i < ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows.Count; i++)
            {

                if (personIdentifier != ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["personIdentifier"].ToString())
                {
                    if (personIdentifier != "")
                    {
						WriteCustomEndElement(objWriter);
                        j2 = 1;
                    }

                    #region ForeignPerson
                    objWriter.WriteStartElement("ForeignPerson", null);


                    WriteAttributeString(objWriter, "personIdentifier", ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["personIdentifier"].ToString());
                    WriteAttributeString(objWriter, "personFirstName", ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["personFirstName"].ToString());
                    WriteAttributeString(objWriter, "personLastName", ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["personLastName"].ToString());
                    WriteAttributeString(objWriter, "birthDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["birthDate"]).ToString("yyyy-MM-dd"));

                    if (ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["countryCode"].ToString() != "")
                        WriteAttributeString(objWriter, "countryCode", ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["countryCode"].ToString());

                    if (ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["cardCode"].ToString() != "")
                        WriteAttributeString(objWriter, "cardCode", ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["personIdentifier"].ToString());

                    if (ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["cardExpireDate"].ToString() != "")
                        WriteAttributeString(objWriter, "cardExpireDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["cardExpireDate"]).ToString("yyyy-MM-dd"));

                    WriteAttributeString(objWriter, "caseId", ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["caseId"].ToString());
                    WriteAttributeString(objWriter, "personType", ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["personType"].ToString());
                    WriteAttributeString(objWriter, "internmentDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["internmentDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "releaseDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["releaseDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "hospitalDeptCode", ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["hospitalDeptCode"].ToString());
                }
                objWriter.WriteStartElement("ForeignProcedure", null);

                WriteAttributeString(objWriter, "procedureCode", ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["procedureCode"].ToString());

				WriteCustomEndElement(objWriter);

                personIdentifier = ds_SIUI_Spital_DRG_Acuti.Tables[3].Rows[i]["personIdentifier"].ToString();
                j2++;

                    #endregion
            }
            //end ForeignPerson 
			WriteCustomEndElement(objWriter);
            //end ForeignPersons
			WriteCustomEndElement(objWriter);
        }

        #endregion

        #region PidLists

        objWriter.WriteStartElement("PidLists", null);
        string sheetNo = "";
        int j3 = 1;
        if (ds_SIUI_Spital_DRG_Acuti.Tables.Count > 4 && ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows.Count > 0)
        {
            for (int i = 0; i < ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows.Count; i++)
            {

                if (sheetNo != ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["sheetNo"].ToString())
                {
                    if (sheetNo != "")
                    {
						WriteCustomEndElement(objWriter);
                        j3 = 1;
                    }
                    #region PidList
                    objWriter.WriteStartElement("PidList", null);


                    WriteAttributeString(objWriter, "AppID", ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["AppID"].ToString());
                    WriteAttributeString(objWriter, "pid", ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["pid"].ToString());
                    WriteAttributeString(objWriter, "birthDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["birthDate"]).ToString("yyyy-MM-dd"));
                    //WriteAttributeString(objWriter, "specialSituationCode", ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["specialSituationCode"].ToString());

                    if (ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["specialSituationCode"].ToString() != "")
                        WriteAttributeString(objWriter, "specialSituationCode", ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["specialSituationCode"].ToString());

                    WriteAttributeString(objWriter, "internmentDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["internmentDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "hospitalDeptCode", ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["hospitalDeptCode"].ToString());
                    WriteAttributeString(objWriter, "releaseDate", Convert.ToDateTime(ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["releaseDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "sheetNo", ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["sheetNo"].ToString());
                    WriteAttributeString(objWriter, "case_id", ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["case_id"].ToString());
                    WriteAttributeString(objWriter, "internmentCriteriaCode", ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["internmentCriteriaCode"].ToString());
                    #endregion
                }
                #region Procedure
                if (ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["procedureCode"].ToString() != "")
                {
                    objWriter.WriteStartElement("Procedure", null);
                    WriteAttributeString(objWriter, "procedureCode", ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["procedureCode"].ToString());
					WriteCustomEndElement(objWriter);
                }
                #endregion
                sheetNo = ds_SIUI_Spital_DRG_Acuti.Tables[4].Rows[i]["sheetNo"].ToString();
                j3++;
            }
			WriteCustomEndElement(objWriter);
        }
		WriteCustomEndElement(objWriter);

        #endregion

        //end report
		WriteCustomEndElement(objWriter);
    }

	private void DoExportSIUI_9(DataSet ds_SIUI_RRR_DializaPeritoneala_Hemodializa, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;
        string[] arrHDDate = new string[10000];

        #region report
        
        objWriter.WriteStartElement("report");
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(parameters.startDate).ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(parameters.endDate).ToString("yyyy-MM-dd"));
        if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables.Count > 0 && ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[0].Rows.Count > 0)
        {
            WriteAttributeString(objWriter, "provider", ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[0].Rows[0]["provider"].ToString());
            WriteAttributeString(objWriter, "fiscalCode", ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "contractNo", ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[0].Rows[0]["contractNo"].ToString());
            WriteAttributeString(objWriter, "insuranceHouse", ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[0].Rows[0]["insuranceHouse"].ToString());
            WriteAttributeString(objWriter, "isCorrection", ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[0].Rows[0]["isCorrection"].ToString());
            WriteAttributeString(objWriter, "supervisorStencilNo", ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[0].Rows[0]["supervisorStencilNo"].ToString());
            WriteAttributeString(objWriter, "AppID", ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[0].Rows[0]["appId"].ToString());
        }

        #endregion

        #region HDs
        objWriter.WriteStartElement("HDs", null);//incepe tagul parinte HDs					

        if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables.Count > 1 && ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows.Count > 0)//verific daca am rezultate
        {
            string pid = "", noHospitalFileDay = "", sessionCharge = "";
            string validFrom = "", validTo = "", obs = "", temporaryTransfer = "", AppID = "", personType = "";
            //initializez variabilele cu ""
            int k = 1;//initializez indicele vectorului cu HDDate-uri
            for (int i = 0; i < ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows.Count; i++)//ciclu pentru toate randurile intoarse din a doua tabela rezultat
            {
                //adaugat nou
                int j;
                for (j = i; j < ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows.Count &&
							ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["AppID"].ToString() == ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[j]["AppID"].ToString()
							// && ds.Tables[1].Rows[i]["pid"].ToString() == ds.Tables[1].Rows[j]["pid"].ToString() && ds.Tables[1].Rows[i]["noHospitalFileDay"].ToString() == ds.Tables[1].Rows[j]["noHospitalFileDay"].ToString() && ds.Tables[1].Rows[i]["sessionCharge"].ToString() == ds.Tables[1].Rows[j]["sessionCharge"].ToString() && ds.Tables[1].Rows[i]["obs"].ToString() == ds.Tables[1].Rows[j]["obs"].ToString() && ds.Tables[1].Rows[i]["temporaryTransfer"].ToString() == ds.Tables[1].Rows[j]["temporaryTransfer"].ToString() && ds.Tables[1].Rows[i]["personType"].ToString() == ds.Tables[1].Rows[j]["personType"].ToString() && ds.Tables[1].Rows[i]["validFrom"].ToString() == ds.Tables[1].Rows[j]["validFrom"].ToString() && ds.Tables[1].Rows[i]["validTo"].ToString() == ds.Tables[1].Rows[j]["validTo"].ToString()
							; j++)
                    //datele sunt ordonate dupa appid
                    if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["HDDate"].ToString() != "")//daca am HDDate-uri le adaug in vector
                    {
                        arrHDDate[k] = Convert.ToDateTime(ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[j]["HDDate"]).ToString("yyyy-MM-dd");
                        //adaug in vectorul HDDate-ul curent
                        k++;//cresc k-ul
                    }
                i = j - 1;//i ia valoarea ultima pentru care datele aveau acelasi appid
                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["AppID"].ToString() != "")
                    AppID = ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["AppID"].ToString();

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["pid"].ToString() != "")
                    pid = ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["pid"].ToString();

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["noHospitalFileDay"].ToString() != "")
                    noHospitalFileDay = ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["noHospitalFileDay"].ToString();

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["sessionCharge"].ToString() != "")
                    sessionCharge = ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["sessionCharge"].ToString();

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["HDDate"].ToString() != "")
                    validFrom = Convert.ToDateTime(ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["HDDate"]).ToString("yyyy-MM-dd");

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["HDDate"].ToString() != "")
                    validTo = Convert.ToDateTime(ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["HDDate"]).ToString("yyyy-MM-dd");

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["obs"].ToString() != "")
                    obs = ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["obs"].ToString();

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["temporaryTransfer"].ToString() != "")
                    temporaryTransfer = ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["temporaryTransfer"].ToString();

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["personType"].ToString() != "")
                    personType = ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["personType"].ToString();
                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["HDDate"].ToString() != "")
                    validTo = Convert.ToDateTime(ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["HDDate"]).ToString("yyyy-MM-dd");
                //end adaugare
                #region HDDate
                if (k > 1)//am valori in vectorul de HDDate-uri
                {
                    objWriter.WriteStartElement("HD", null);//incepe tagul HD
                    //if ("AppID" != "")
                    WriteAttributeString(objWriter, "AppID", AppID);

                    //if ("pid" != "")
                    WriteAttributeString(objWriter, "pid", pid);

                    //if ("noHospitalFileDay" != "")
                    WriteAttributeString(objWriter, "noHospitalFileDay", noHospitalFileDay);

                    WriteAttributeString(objWriter, "noReportedHemSession", Convert.ToString(k - 1));

                    //if ("sessionCharge" != "")
                    WriteAttributeString(objWriter, "sessionCharge", sessionCharge);

                    WriteAttributeString(objWriter, "reportedRefoundSumE", Convert.ToString((k - 1) * Convert.ToDecimal(sessionCharge)));
                    //					WriteAttributeString(objWriter, "validFrom", validFrom);
                    //					WriteAttributeString(objWriter, "validTo", validTo);				
                    WriteAttributeString(objWriter, "validFrom", Convert.ToDateTime(ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["validFrom"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "validTo", Convert.ToDateTime(ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[1].Rows[i]["validTo"]).ToString("yyyy-MM-dd"));
                    //if ("obs" != "") 
                    WriteAttributeString(objWriter, "obs", obs);

                    //if ("temporaryTransfer" != "") 
                    WriteAttributeString(objWriter, "temporaryTransfer", temporaryTransfer);

                    //if ("personType" != "")
                    WriteAttributeString(objWriter, "personType", personType);

                    for (int t = 1; t < k; t++)
                    {//scriu datele pentru tag-ul HDDate
                        objWriter.WriteStartElement("HDDate", null);  //incep tagul HDDate
                        WriteAttributeString(objWriter, "date", arrHDDate[t].ToString());
						WriteCustomEndElement(objWriter);  //inchid tag-ul HDDate
                    }//end scriere HDDate
                    k = 1;//reinitializez indicele
                    Array.Clear(arrHDDate, 0, arrHDDate.Length);//curat vectorul de HDDate-uri

					WriteCustomEndElement(objWriter);//inchid tag-ul HD
                    objWriter.Flush();
                }	//inchid verificarea daca am mai multe valori in vectorul de HDDate-uri
                #endregion


                #region HD

                //end HD

                #endregion
            }//inchid for-ul dupa toate rezultatele din a doua tabela rezultat
        }//inchid verificarea daca am date in a doua tabela rezultat						
        else
        {
            objWriter.WriteStartElement("HD", null);
            objWriter.WriteStartElement("HDDate", null);
			WriteCustomEndElement(objWriter);
			WriteCustomEndElement(objWriter);
        }
        //end HDs
		WriteCustomEndElement(objWriter);
        objWriter.Flush();
        #endregion

        #region DPs
        objWriter.WriteStartElement("DPs", null);

        if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables.Count > 2 && ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows.Count > 0)
        {
            for (int i = 0; i < ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows.Count; i++)
            {

                #region DP
                objWriter.WriteStartElement("DP", null);
                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["AppID"].ToString() != "")
                    WriteAttributeString(objWriter, "AppID", ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["AppID"].ToString());

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["pid"].ToString() != "")
                    WriteAttributeString(objWriter, "pid", ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["pid"].ToString());

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["noHospitalFileDay"].ToString() != "")
                    WriteAttributeString(objWriter, "noHospitalFileDay", ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["noHospitalFileDay"].ToString());

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["reportedRefoundSumE"].ToString() != "")
                    WriteAttributeString(objWriter, "reportedRefoundSumE", ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["reportedRefoundSumE"].ToString());

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["validFrom"].ToString() != "")
                    WriteAttributeString(objWriter, "validFrom", Convert.ToDateTime(ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["validFrom"]).ToString("yyyy-MM-dd"));

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["validTo"].ToString() != "")
                    WriteAttributeString(objWriter, "validTo", Convert.ToDateTime(ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["validTo"]).ToString("yyyy-MM-dd"));
                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["obs"].ToString() != "")
                    WriteAttributeString(objWriter, "obs", ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["obs"].ToString());

                if (ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["personType"].ToString() != "")
                    WriteAttributeString(objWriter, "personType", ds_SIUI_RRR_DializaPeritoneala_Hemodializa.Tables[2].Rows[i]["personType"].ToString());
				WriteCustomEndElement(objWriter);
                #endregion
            }
        }
        else
        {
            objWriter.WriteStartElement("DP", null);
			WriteCustomEndElement(objWriter);
        }

        //end DPs
		WriteCustomEndElement(objWriter);
        objWriter.Flush();
        #endregion

		WriteCustomEndElement(objWriter);//inchid tagul report
    }

	private void DoExportSIUI_10(DataSet ds_SIUI_PNS, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;
        string[] arrHDDate = new string[10000];
        Hashtable GoodsConsumptionAppGc = new Hashtable();
        Hashtable GoodsAppGc = new Hashtable();
        #region report
        
        objWriter.WriteStartElement("report");//incepe tag-ul report
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "reportStartDate", Convert.ToDateTime(parameters.startDate).ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "reportEndDate", Convert.ToDateTime(parameters.endDate).ToString("yyyy-MM-dd"));

        if (ds_SIUI_PNS.Tables.Count > 0 && ds_SIUI_PNS.Tables[0].Rows.Count > 0)
        {//verific daca am date in prima tabela intoarsa din baza de date
            //atributul este obligatoriu
            WriteAttributeString(objWriter, "NHP", ds_SIUI_PNS.Tables[0].Rows[0]["NHP"].ToString());
            //atribut obligatoriu
            WriteAttributeString(objWriter, "medicalServiceProviderCUI",
                                           ds_SIUI_PNS.Tables[0].Rows[0]["medicalServiceProviderCUI"].ToString());
            //atribut obligatoriu
            WriteAttributeString(objWriter, "medicalServiceProviderName",
                                           ds_SIUI_PNS.Tables[0].Rows[0]["medicalServiceProviderName"].ToString());

            //atribut obligatoriu
            WriteAttributeString(objWriter, "reportType", ds_SIUI_PNS.Tables[0].Rows[0]["reportType"].ToString());

            if (ds_SIUI_PNS.Tables[0].Rows[0]["contractNo"].ToString() != "")
                WriteAttributeString(objWriter, "contractNo", ds_SIUI_PNS.Tables[0].Rows[0]["contractNo"].ToString());
            if (ds_SIUI_PNS.Tables[0].Rows[0]["contractYear"].ToString() != "")
                WriteAttributeString(objWriter, "contractYear", ds_SIUI_PNS.Tables[0].Rows[0]["contractYear"].ToString());
            //atribut obligatoriu
            WriteAttributeString(objWriter, "reportNo", ds_SIUI_PNS.Tables[0].Rows[0]["reportNo"].ToString());

        }//end verificare daca sunt date in prima tabela returnata din baza de date

        #region persons
        string cnp = "";
        string appidgc = "";
        string[] visitedCNP;
		visitedCNP = new string[ds_SIUI_PNS.Tables[1].Rows.Count]; //TODO: Replace with a HashSet<string>, or HashTable<string>
        int count = -1;
        int isVisited = -1;

        if (ds_SIUI_PNS.Tables.Count > 1 && ds_SIUI_PNS.Tables[1].Rows.Count > 0)//verificare daca am date in a doua tabela returnata din BD
        {
            objWriter.WriteStartElement("persons", null);	//incepe tag-ul persons
            for (int i = 0; i < ds_SIUI_PNS.Tables[1].Rows.Count; i++) //primul for
            {
                //verific daca CNP-ul a mai fost vizitat, daca nu il introduc in vectorul cu noduri vizitate
                isVisited = 0;
                for (int l = 0; l <= count; l++)
                    if (visitedCNP[l] == ds_SIUI_PNS.Tables[1].Rows[i]["CNP"].ToString())
                        isVisited = 1;
                if (isVisited == 0)
                {
                    count++;
                    visitedCNP[count] = ds_SIUI_PNS.Tables[1].Rows[i]["CNP"].ToString();
                }
                #region Person
                //end verificare daca CNP-ul a mai fost vizitat
                if (cnp != ds_SIUI_PNS.Tables[1].Rows[i]["CNP"].ToString() && isVisited == 0)
                {//verific vechiul cnp cu cel nou
                    if (cnp != "")
                    {
                        //inseamna ca variabila cnp a fost modificata cu o alta valoare, 
                        //trebuie inchis tag-ul person pentru cnp-ul vechi
						WriteCustomEndElement(objWriter);//person

                    }//inchid tag-ul person pentru valoarea precedenta a cnp-ului
                    objWriter.WriteStartElement("person", null); //incepe tag-ul persons din nou!!!
                    //atribut obligatoriu
                    WriteAttributeString(objWriter, "cnp", ds_SIUI_PNS.Tables[1].Rows[i]["CNP"].ToString());
                    //atribut obligatoriu
                    WriteAttributeString(objWriter, "name", ds_SIUI_PNS.Tables[1].Rows[i]["NAME"].ToString());
                    //atribut obligatoriu
                    WriteAttributeString(objWriter, "categoryCode", ds_SIUI_PNS.Tables[1].Rows[i]["categoryCode"].ToString());
                    WriteAttributeString(objWriter, "startDate",
                        Convert.ToDateTime(ds_SIUI_PNS.Tables[1].Rows[i]["startDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "endDate",
                        Convert.ToDateTime(ds_SIUI_PNS.Tables[1].Rows[i]["endDate"]).ToString("yyyy-MM-dd"));
                    cnp = ds_SIUI_PNS.Tables[1].Rows[i]["CNP"].ToString();//cnp-ul ia valoarea curenta

                #endregion
                    int cntGoodsConsAppIdGc = 0;
                    int cntGoodAppIdGc = 0;
                    #region TherapeuticalSchemas
                    for (int j = i; j < ds_SIUI_PNS.Tables[1].Rows.Count; j++)
                    {
                        if (cnp == ds_SIUI_PNS.Tables[1].Rows[j]["CNP"].ToString())
                        {
                            if (i == j)
                            {
                                //incepe tagul parinte de scheme terapeutice
                                objWriter.WriteStartElement("TherapeuticalSchemas", null);
                            }
                            //if (appid != ds_SIUI_PNS.Tables[1].Rows[j]["AppID_ths"].ToString())
                            if (!GoodsConsumptionAppGc.ContainsValue(ds_SIUI_PNS.Tables[1].Rows[j]["AppID_gc"].ToString()))
                            {//verific daca valoarea variabilei appid difera de valoarea curenta 
                                objWriter.WriteStartElement("TherapeuticalSchema", null);//incepe tagul schemei terapeutice
                                //atribut obligatoriu
                                WriteAttributeString(objWriter, "code", ds_SIUI_PNS.Tables[1].Rows[j]["code_ths"].ToString());
                                //atribut obligatoriu
                                WriteAttributeString(objWriter, "diagCode", ds_SIUI_PNS.Tables[1].Rows[j]["diagCode_ths"].ToString());
                                WriteAttributeString(objWriter, "categoryCode",
                                    ds_SIUI_PNS.Tables[1].Rows[j]["categoryCode_ths"].ToString());
                                if (ds_SIUI_PNS.Tables[1].Rows[j]["validFrom_ths"] != DBNull.Value)
                                    WriteAttributeString(objWriter, "validFrom",
                                        Convert.ToDateTime(ds_SIUI_PNS.Tables[1].Rows[j]["validFrom_ths"]).ToString("yyyy-MM-dd"));
                                else //atribut obligatoriu
                                    WriteAttributeString(objWriter, "validFrom", "");
                                if (ds_SIUI_PNS.Tables[1].Rows[j]["validTo_ths"] != DBNull.Value)
                                    WriteAttributeString(objWriter, "validTo",
                                        Convert.ToDateTime(ds_SIUI_PNS.Tables[1].Rows[j]["validTo_ths"]).ToString("yyyy-MM-dd"));
                                //atribut obligatoriu
                                WriteAttributeString(objWriter, "AppID", ds_SIUI_PNS.Tables[1].Rows[j]["AppID_ths"].ToString());
                                appidgc = ds_SIUI_PNS.Tables[1].Rows[j]["AppID_gc"].ToString();//appidgc ia valoarea curenta
                                GoodsConsumptionAppGc[(cntGoodsConsAppIdGc++).ToString()] = ds_SIUI_PNS.Tables[1].Rows[j]["AppID_gc"].ToString();

                                for (int k = 0; k < ds_SIUI_PNS.Tables[1].Rows.Count; k++) //al doilea for
                                {
                                    if (appidgc == ds_SIUI_PNS.Tables[1].Rows[k]["AppID_gc"].ToString() && appidgc != "" && !GoodsAppGc.ContainsValue(ds_SIUI_PNS.Tables[1].Rows[k]["AppID_g"].ToString()))
                                    //if (appid == ds_SIUI_PNS.Tables[1].Rows[k]["AppID_ths"].ToString() && appid != "")
                                    {//verific unde, prin rezultatele celei de-a doua tabele, sunt datele cu acelasi appid	
                                        if (ds_SIUI_PNS.Tables[1].Rows[k]["code_scd"] != DBNull.Value
                                            && ds_SIUI_PNS.Tables[1].Rows[k]["type_scd"] != DBNull.Value
                                            && ds_SIUI_PNS.Tables[1].Rows[k]["quantity_scd"] != DBNull.Value
                                            && ds_SIUI_PNS.Tables[1].Rows[k]["AppID_scd"] != DBNull.Value
                                            && ds_SIUI_PNS.Tables[1].Rows[k]["date_scd"] != DBNull.Value)
                                        {
                                            objWriter.WriteStartElement("SchemaDrug", null);
                                            WriteAttributeString(objWriter, "code",
                                                ds_SIUI_PNS.Tables[1].Rows[k]["code_scd"].ToString());
                                            WriteAttributeString(objWriter, "type",
                                                ds_SIUI_PNS.Tables[1].Rows[k]["type_scd"].ToString());
                                            WriteAttributeString(objWriter, "quantity", Tools.GetNumberInEnglishFormat(ds_SIUI_PNS.Tables[1].Rows[k]["quantity_scd"].ToString()));
                                            WriteAttributeString(objWriter, "AppID",
                                                ds_SIUI_PNS.Tables[1].Rows[k]["AppID_scd"].ToString());
                                            WriteAttributeString(objWriter, "date",
                                                Convert.ToDateTime(ds_SIUI_PNS.Tables[1].Rows[k]["date_scd"]).ToString("yyyy-MM-dd"));
											WriteCustomEndElement(objWriter);
                                            objWriter.Flush(); //poate merge mai repede asa
                                        }
                                    }//inchid verificarea datelor cu acelasi appid

                                    GoodsAppGc[(cntGoodAppIdGc++).ToString()] = ds_SIUI_PNS.Tables[1].Rows[k]["AppID_g"].ToString();
                                }//inchid al doilea for

                                GoodsAppGc.Clear();

								WriteCustomEndElement(objWriter);//inchid therapeutical schema
                                objWriter.Flush(); //poate merge mai repede asa
                            }//inchid verificarea daca appid este diferita de valoarea curenta
                            objWriter.Flush(); //poate merge mai repede asa
                        }//inchid verificarea datelor pentru acelasi cnp din a doua tabela
                    }//inchid for-ul care merge incepand de la pozitia i prin toata tabela a doua a rezultatului
					WriteCustomEndElement(objWriter);//inchid therapeutical schemaS
                    #endregion

                    #region GoodsConsumptions
                    for (int j = i; j < ds_SIUI_PNS.Tables[1].Rows.Count; j++)
                    {
                        if (cnp == ds_SIUI_PNS.Tables[1].Rows[j]["CNP"].ToString())
                        {
                            if (i == j)
                            {
                                objWriter.WriteStartElement("GoodsConsumptions", null);
                            }
                            if (appidgc != ds_SIUI_PNS.Tables[1].Rows[j]["AppID_gc"].ToString())
                            {//verific daca appidgc difera de valoarea curenta
                                if (ds_SIUI_PNS.Tables[1].Rows[j]["code_gc"] != DBNull.Value
                                    && ds_SIUI_PNS.Tables[1].Rows[j]["categoryCode_gc"] != DBNull.Value
                                    && ds_SIUI_PNS.Tables[1].Rows[j]["consumptionDate_gc"] != DBNull.Value
                                    && ds_SIUI_PNS.Tables[1].Rows[j]["AppID_gc"] != DBNull.Value)
                                {
                                    objWriter.WriteStartElement("GoodsConsumption", null);
                                    //atribut obligatoriu
                                    WriteAttributeString(objWriter, "code", ds_SIUI_PNS.Tables[1].Rows[j]["code_gc"].ToString());
                                    //atribut obligatoriu
                                    WriteAttributeString(objWriter, "categoryCode",
                                                                   ds_SIUI_PNS.Tables[1].Rows[j]["categoryCode_gc"].ToString());
                                    if (ds_SIUI_PNS.Tables[1].Rows[j]["consumptionDate_gc"] != DBNull.Value)
                                        WriteAttributeString(objWriter, "consumptionDate",
                                        Convert.ToDateTime(ds_SIUI_PNS.Tables[1].Rows[j]["consumptionDate_gc"]).ToString("yyyy-MM-dd"));
                                    //atribut obligatoriu
                                    WriteAttributeString(objWriter, "AppID", ds_SIUI_PNS.Tables[1].Rows[j]["AppID_gc"].ToString());
                                    appidgc = ds_SIUI_PNS.Tables[1].Rows[j]["AppID_gc"].ToString();//appidgc ia valoarea curenta

                                    for (int m = 0; m < ds_SIUI_PNS.Tables[1].Rows.Count; m++)//acelasi nivel cu al doilea for
                                    {
                                        if (appidgc == ds_SIUI_PNS.Tables[1].Rows[m]["AppID_gc"].ToString() && appidgc != "")
                                        {
                                            //verific unde, printre rezultatele celei de-a doua tabele, 
                                            //sunt datele cu acelasi appidgc
                                            objWriter.WriteStartElement("Good", null);
                                            //atribut obligatoriu
                                            WriteAttributeString(objWriter, "code", ds_SIUI_PNS.Tables[1].Rows[m]["code_g"].ToString());
                                            if (ds_SIUI_PNS.Tables[1].Rows[m]["quantity_g"] != DBNull.Value)
                                                WriteAttributeString(objWriter, "quantity",
                                                    ds_SIUI_PNS.Tables[1].Rows[m]["quantity_g"].ToString());
                                            else //atribut obligatoriu
                                                WriteAttributeString(objWriter, "quantity", "");
                                            if (ds_SIUI_PNS.Tables[1].Rows[m]["unitPrice_g"] != DBNull.Value)
                                                WriteAttributeString(objWriter, "unitPrice",
                                                                               ds_SIUI_PNS.Tables[1].Rows[m]["unitPrice_g"].ToString());
                                            else //atribut obligatoriu
                                                WriteAttributeString(objWriter, "unitPrice", "");
                                            if (ds_SIUI_PNS.Tables[1].Rows[m]["VATPercent_g"] != DBNull.Value)
                                                WriteAttributeString(objWriter, "VATPercent",
                                                    ds_SIUI_PNS.Tables[1].Rows[m]["VATPercent_g"].ToString());
                                            else //atribut obligatoriu
                                                WriteAttributeString(objWriter, "VATPercent", "");
                                            if (ds_SIUI_PNS.Tables[1].Rows[m]["AppID_g"] != DBNull.Value)
                                                WriteAttributeString(objWriter, "AppID",
                                                                               ds_SIUI_PNS.Tables[1].Rows[m]["AppID_g"].ToString());
                                            else //atribut obligatoriu
                                                WriteAttributeString(objWriter, "AppID", "");
											WriteCustomEndElement(objWriter);
                                            objWriter.Flush(); //poate merge mai repede asa
                                        }//inchid verificarea datelor cu acelasi appidgc
                                    }//inchid for-ul de nivel doi
									WriteCustomEndElement(objWriter);//inchid goods consumption
                                    objWriter.Flush(); //poate merge mai repede asa
                                }
                            }//inchid verificarea daca appidgc difera de valoarea curenta
                            objWriter.Flush(); //poate merge mai repede asa
                        }//inchid verificarea datelor pentru acelasi cnp din a doua tabela
                    }//inchid for-ul care parcurge restul datelor din cea de-a doua tabela, pornind de la pozitia lui i
					WriteCustomEndElement(objWriter);//inchid goods consumptionS
                }//inchid verificarea vechiului cnp cu cel nou
            }//inchid primul for
                    #endregion
			WriteCustomEndElement(objWriter);//end last person

			WriteCustomEndElement(objWriter);//end persons
            objWriter.Flush(); //poate merge mai repede asa
        }

        #endregion

        #region Indicators

        if (ds_SIUI_PNS.Tables.Count > 2 && ds_SIUI_PNS.Tables[2].Rows.Count > 0)
        {
            //verific daca am date in cea de-a treia tabela din BD
            objWriter.WriteStartElement("indicators", null);
            for (int i = 0; i < ds_SIUI_PNS.Tables[2].Rows.Count; i++)
            {
                if (ds_SIUI_PNS.Tables[2].Rows[i]["tab1"].ToString() != "")
                {

                    objWriter.WriteStartElement("indicator", null);

                    if (ds_SIUI_PNS.Tables[2].Rows[i]["tab1"].ToString() != "")
                        WriteAttributeString(objWriter, "code", ds_SIUI_PNS.Tables[2].Rows[i]["tab1"].ToString());

                    if (ds_SIUI_PNS.Tables[2].Rows[i]["tab2"].ToString() != "")
                        WriteAttributeString(objWriter, "value", ds_SIUI_PNS.Tables[2].Rows[i]["tab2"].ToString());

					WriteCustomEndElement(objWriter);
                }
            }
			WriteCustomEndElement(objWriter);//indicators
        }//inchid verificarea daca am date in cea de-a treia tabela returnata din BD

        #endregion

		WriteCustomEndElement(objWriter);//end report
        #endregion
    }

	private void DoExportSIUI_11(DataSet ds_SIUI_PNS_NhpCJ, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;
        string[] arrHDDate = new string[10000];

        #region report
        
        objWriter.WriteStartElement("report");
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(parameters.startDate).ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(parameters.endDate).ToString("yyyy-MM-dd"));
        if (ds_SIUI_PNS_NhpCJ.Tables.Count > 0 && ds_SIUI_PNS_NhpCJ.Tables[0].Rows.Count > 0)
        {
            WriteAttributeString(objWriter, "provider", ds_SIUI_PNS_NhpCJ.Tables[0].Rows[0]["provider"].ToString());
            WriteAttributeString(objWriter, "fiscalCode", ds_SIUI_PNS_NhpCJ.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "contractNo", ds_SIUI_PNS_NhpCJ.Tables[0].Rows[0]["contractNo"].ToString());
            WriteAttributeString(objWriter, "insuranceHouse", ds_SIUI_PNS_NhpCJ.Tables[0].Rows[0]["insuranceHouse"].ToString());
            WriteAttributeString(objWriter, "contractYear", ds_SIUI_PNS_NhpCJ.Tables[0].Rows[0]["contractYear"].ToString());
            WriteAttributeString(objWriter, "centralizerNo", ds_SIUI_PNS_NhpCJ.Tables[0].Rows[0]["centralizerNo"].ToString());
            WriteAttributeString(objWriter, "appID", ds_SIUI_PNS_NhpCJ.Tables[0].Rows[0]["appId"].ToString());
            WriteAttributeString(objWriter, "Nhp", ds_SIUI_PNS_NhpCJ.Tables[0].Rows[0]["Nhp"].ToString());
        }

        #endregion

        #region facturi

        string appID = "";
        int j = 1;
        if (ds_SIUI_PNS_NhpCJ.Tables.Count > 1 && ds_SIUI_PNS_NhpCJ.Tables[1].Rows.Count > 0)
        {
            objWriter.WriteStartElement("facturi", null);
            for (int i = 0; i < ds_SIUI_PNS_NhpCJ.Tables[1].Rows.Count; i++)
            {

                if (appID != ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["appId"].ToString())
                {
                    if (appID != "")
                    {
						WriteCustomEndElement(objWriter);
                        j = 1;
                    }
                    #region factura
                    objWriter.WriteStartElement("factura", null);

                    WriteAttributeString(objWriter, "noInvoice", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["noInvoice"].ToString());
                    WriteAttributeString(objWriter, "dateInvoice",
                        Convert.ToDateTime(ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["dateInvoice"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "totalValue", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["totalValue"].ToString());
                    WriteAttributeString(objWriter, "appID", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["appID"].ToString());

                    #endregion
                }
                #region articol
                objWriter.WriteStartElement("articol", null);

                WriteAttributeString(objWriter, "code", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["code"].ToString());
                WriteAttributeString(objWriter, "articleType", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["articleType"].ToString());
                WriteAttributeString(objWriter, "qty", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["qty"].ToString());
                WriteAttributeString(objWriter, "vat", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["vat"].ToString());
                WriteAttributeString(objWriter, "vatValue", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["vatValue"].ToString());
                WriteAttributeString(objWriter, "totalValueWOTVA", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["totalValueWOTVA"].ToString());
                WriteAttributeString(objWriter, "totalValue", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["totalValue_Articol"].ToString());
                WriteAttributeString(objWriter, "unitPrice", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["unitPrice"].ToString());
                WriteAttributeString(objWriter, "appID", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["appID_articol"].ToString());
                WriteAttributeString(objWriter, "allocationType", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["allocationType"].ToString());

                if (ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["indicatorCode"].ToString() != "")
                    WriteAttributeString(objWriter, "indicatorCode", ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["indicatorCode"].ToString());

				WriteCustomEndElement(objWriter);
                #endregion

                appID = ds_SIUI_PNS_NhpCJ.Tables[1].Rows[i]["appId"].ToString();
                j++;
            }
			WriteCustomEndElement(objWriter);
            //end facturi
			WriteCustomEndElement(objWriter);
        }

        #endregion

        #region ops

        if (ds_SIUI_PNS_NhpCJ.Tables.Count > 2 && ds_SIUI_PNS_NhpCJ.Tables[2].Rows.Count > 0)
        {
            objWriter.WriteStartElement("ops", null);
            for (int x = 0; x < ds_SIUI_PNS_NhpCJ.Tables[2].Rows.Count; x++)
            {
                #region op
                objWriter.WriteStartElement("op", null);


                WriteAttributeString(objWriter, "noOp", ds_SIUI_PNS_NhpCJ.Tables[2].Rows[x]["noOp"].ToString());
                WriteAttributeString(objWriter, "dateOp",
                    Convert.ToDateTime(ds_SIUI_PNS_NhpCJ.Tables[2].Rows[x]["dateOp"]).ToString("yyyy-MM-dd"));
                WriteAttributeString(objWriter, "valueOp", ds_SIUI_PNS_NhpCJ.Tables[2].Rows[x]["valueOp"].ToString());

                if (ds_SIUI_PNS_NhpCJ.Tables[2].Rows[x]["obs"].ToString() != "")
                    WriteAttributeString(objWriter, "obs", ds_SIUI_PNS_NhpCJ.Tables[2].Rows[x]["obs"].ToString());

                WriteAttributeString(objWriter, "appID", ds_SIUI_PNS_NhpCJ.Tables[2].Rows[x]["appID"].ToString());

                //end Op
				WriteCustomEndElement(objWriter);
                #endregion
            }
            //end Ops
			WriteCustomEndElement(objWriter);
        }

        #endregion

        //end report
		WriteCustomEndElement(objWriter);
    }

	private void DoExportSIUI_12(DataSet ds_SIUI_REC_AMB, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;
        string[] arrHDDate = new string[10000];

        #region report
        
        objWriter.WriteStartElement("report");//incepe tag-ul report
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(parameters.startDate).ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(parameters.endDate).ToString("yyyy-MM-dd"));
        if (ds_SIUI_REC_AMB.Tables.Count > 0 && ds_SIUI_REC_AMB.Tables[0].Rows.Count > 0)
        {//verific daca am date in prima tabela intoarsa din baza de date
            //if (ds.Tables[0].Rows[0]["AppKey"].ToString() != "") 
            //WriteAttributeString(objWriter, "AppKey",ds.Tables[0].Rows[0]["AppKey"].ToString());
            WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_AMB.Tables[0].Rows[0]["AppId"].ToString());
            WriteAttributeString(objWriter, "medicalUnit", ds_SIUI_REC_AMB.Tables[0].Rows[0]["medicalUnit"].ToString());
            WriteAttributeString(objWriter, "fiscalCode", ds_SIUI_REC_AMB.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "contractNo", ds_SIUI_REC_AMB.Tables[0].Rows[0]["contractNo"].ToString());
            WriteAttributeString(objWriter, "insuranceHouse", ds_SIUI_REC_AMB.Tables[0].Rows[0]["insuranceHouse"].ToString());
            if (ds_SIUI_REC_AMB.Tables[0].Rows[0]["invoiceNo"].ToString() != "")
                WriteAttributeString(objWriter, "invoiceNo", ds_SIUI_REC_AMB.Tables[0].Rows[0]["invoiceNo"].ToString());
            if (ds_SIUI_REC_AMB.Tables[0].Rows[0]["invoiceDate"].ToString() != "")
                WriteAttributeString(objWriter, "invoiceDate", ds_SIUI_REC_AMB.Tables[0].Rows[0]["invoiceDate"].ToString());
            if (ds_SIUI_REC_AMB.Tables[0].Rows[0]["invoiceValue"].ToString() != "")
                WriteAttributeString(objWriter, "invoiceValue", ds_SIUI_REC_AMB.Tables[0].Rows[0]["invoiceValue"].ToString());
        }//end verificare daca sunt date in prima tabela returnata din baza de date

        #region recoveryAmbServices
        string appid1 = "";
        string appid = "";
        string appidgc = "";
        string appidgc2 = "";
        string[] visitedAppid;
        visitedAppid = new string[ds_SIUI_REC_AMB.Tables[1].Rows.Count];
        int count = -1;
        int isVisited = -1;

        //verificare daca am date in a doua tabela returnata din BD
        if (ds_SIUI_REC_AMB.Tables.Count > 1 && ds_SIUI_REC_AMB.Tables[1].Rows.Count > 0)
        {
            objWriter.WriteStartElement("recoveryAmbServices", null);	//incepe tag-ul recoveryAmbServices
            for (int i = 0; i < ds_SIUI_REC_AMB.Tables[1].Rows.Count; i++) //primul for
            {
                //verific daca APPID-ul a mai fost vizitat, daca nu il introduc in vectorul cu noduri vizitate
                isVisited = 0;
                for (int l = 0; l <= count; l++)
                    if (visitedAppid[l] == ds_SIUI_REC_AMB.Tables[1].Rows[i]["AppId"].ToString())
                        isVisited = 1;
                if (isVisited == 0)
                {
                    count++;
                    visitedAppid[count] = ds_SIUI_REC_AMB.Tables[1].Rows[i]["AppId"].ToString();
                }

                #region recoveryAmbService
                //end verificare daca Appid-ul a mai fost vizitat
                if (appid1 != ds_SIUI_REC_AMB.Tables[1].Rows[i]["Appid"].ToString() && isVisited == 0)
                {//verific vechiul appid cu cel nou
                    if (appid1 != "")
                    {
                        //inseamna ca variabila appId a fost modificata cu o alta valoare, trebuie inchis tag-ul
                        //recoveryAmbService pentru appid-ul vechi
						WriteCustomEndElement(objWriter);//recoveryAmbService

                    }//inchid tag-ul recoveryAmbService pentru valoarea precedenta a AppId-ului
                    objWriter.WriteStartElement("recoveryAmbService", null); //incepe tag-ul recoveryAmbService din nou!!!
                    WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_AMB.Tables[1].Rows[i]["AppID"].ToString());
                    WriteAttributeString(objWriter, "personType", ds_SIUI_REC_AMB.Tables[1].Rows[i]["personType"].ToString());
                    WriteAttributeString(objWriter, "personIdentifier",
                        ds_SIUI_REC_AMB.Tables[1].Rows[i]["personIdentifier"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["personFirstName"].ToString() != "")
                        WriteAttributeString(objWriter, "personFirstName", ds_SIUI_REC_AMB.Tables[1].Rows[i]["personFirstName"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["personLastName"].ToString() != "")
                        WriteAttributeString(objWriter, "personLastName", ds_SIUI_REC_AMB.Tables[1].Rows[i]["personLastName"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["birthDate"].ToString() != "")
                        WriteAttributeString(objWriter, "birthDate",
                            Convert.ToDateTime(ds_SIUI_REC_AMB.Tables[1].Rows[i]["birthDate"]).ToString("yyyy-MM-dd"));

                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["emissiveOrgUnitName"].ToString() != "")
                        WriteAttributeString(objWriter, "emissiveOrgUnitName",
                            ds_SIUI_REC_AMB.Tables[1].Rows[i]["emissiveOrgUnitName"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["emissiveOrgUnitAddress"].ToString() != "")
                        WriteAttributeString(objWriter, "emissiveOrgUnitAddress",
                            ds_SIUI_REC_AMB.Tables[1].Rows[i]["emissiveOrgUnitAddress"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["emissiveOrgUnitUIC"].ToString() != "")
                        WriteAttributeString(objWriter, "emissiveOrgUnitUIC",
                            ds_SIUI_REC_AMB.Tables[1].Rows[i]["emissiveOrgUnitUIC"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["country"].ToString() != "")
                        WriteAttributeString(objWriter, "country", ds_SIUI_REC_AMB.Tables[1].Rows[i]["country"].ToString());
                    WriteAttributeString(objWriter, "presentationMode", ds_SIUI_REC_AMB.Tables[1].Rows[i]["presentationMode"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedByNo"].ToString() != "")
                        WriteAttributeString(objWriter, "refferedByNo", ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedByNo"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedBySerialCode"].ToString() != "")
                        WriteAttributeString(objWriter, "refferedBySerialCode",
                            ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedBySerialCode"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedByStencilNo"].ToString() != "")
                        WriteAttributeString(objWriter, "refferedByStencilNo",
                            ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedByStencilNo"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedByDate"].ToString() != "")
                        WriteAttributeString(objWriter, "refferedByDate", ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedByDate"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedBySpecialty"].ToString() != "")
                        WriteAttributeString(objWriter, "refferedBySpecialty",
                            ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedBySpecialty"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedByContractNo"].ToString() != "")
                        WriteAttributeString(objWriter, "refferedByContractNo",
                            ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedByContractNo"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedByOrgUnitCode"].ToString() != "")
                        WriteAttributeString(objWriter, "refferedByOrgUnitCode",
                            ds_SIUI_REC_AMB.Tables[1].Rows[i]["refferedByOrgUnitCode"].ToString());
                    WriteAttributeString(objWriter, "merNo", ds_SIUI_REC_AMB.Tables[1].Rows[i]["merNo"].ToString());
                    WriteAttributeString(objWriter, "merDate",
                        Convert.ToDateTime(ds_SIUI_REC_AMB.Tables[1].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));

                    appid1 = ds_SIUI_REC_AMB.Tables[1].Rows[i]["AppId"].ToString();//appid-ul ia valoarea curenta
                #endregion

                    #region Services
                    for (int j = i; j < ds_SIUI_REC_AMB.Tables[1].Rows.Count; j++)
                    {
                        if (appid1 == ds_SIUI_REC_AMB.Tables[1].Rows[j]["AppId"].ToString())
                        {
                            if (i == j)
                            {
                                objWriter.WriteStartElement("services", null);//incepe tagul parinte de servicii
                            }
                            if (appid != ds_SIUI_REC_AMB.Tables[1].Rows[j]["AppID_ths"].ToString())
                            {//verific daca valoarea variabilei appid difera de valoarea curenta 
                                objWriter.WriteStartElement("service", null);//incepe tagul serviciului
                                WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_AMB.Tables[1].Rows[j]["AppID_ths"].ToString());
                                WriteAttributeString(objWriter, "code", ds_SIUI_REC_AMB.Tables[1].Rows[j]["code"].ToString());
                                WriteAttributeString(objWriter, "date",
                                    Convert.ToDateTime(ds_SIUI_REC_AMB.Tables[1].Rows[j]["date"]).ToString("yyyy-MM-dd"));
                                WriteAttributeString(objWriter, "stencilNo", ds_SIUI_REC_AMB.Tables[1].Rows[j]["stencilNo"].ToString());
                                if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["reportedPrice"].ToString() != "")
                                    WriteAttributeString(objWriter, "reportedPrice",
                                        ds_SIUI_REC_AMB.Tables[1].Rows[j]["reportedPrice"].ToString());

                                appid = ds_SIUI_REC_AMB.Tables[1].Rows[j]["AppID_ths"].ToString();//appid ia valoarea curenta

								WriteCustomEndElement(objWriter);//inchid Service
                                objWriter.Flush(); //poate merge mai repede asa
                            }//inchid verificarea daca appid este diferita de valoarea curenta
                            objWriter.Flush(); //poate merge mai repede asa
                        }//inchid verificarea datelor pentru acelasi appid din a doua tabela
                    }//inchid for-ul care merge incepand de la pozitia i prin toata tabela a doua a rezultatului
					WriteCustomEndElement(objWriter);//inchid ServiceS

                    #endregion

                    #region diagnostics

                    objWriter.WriteStartElement("diagnostics", null);//incepe tag-ul Diagnostics
                    if (appidgc != ds_SIUI_REC_AMB.Tables[1].Rows[i]["AppID"].ToString())
                    {//verific daca appidgc difera de valoarea curenta

                        objWriter.WriteStartElement("diagnostic", null);
                        WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_AMB.Tables[1].Rows[i]["AppID"].ToString());
                        WriteAttributeString(objWriter, "name", ds_SIUI_REC_AMB.Tables[1].Rows[i]["name3"].ToString());
                        if (ds_SIUI_REC_AMB.Tables[1].Rows[i]["name"].ToString() != "")
                            WriteAttributeString(objWriter, "name", ds_SIUI_REC_AMB.Tables[1].Rows[i]["name3"].ToString());
                        appid = ds_SIUI_REC_AMB.Tables[1].Rows[i]["AppID"].ToString();//appidgc ia valoarea curenta

						WriteCustomEndElement(objWriter);//inchid diagnostic
                        objWriter.Flush(); //poate merge mai repede asa

                    }//inchid verificarea daca appidgc difera de valoarea curenta
                    objWriter.Flush(); //poate merge mai repede asa
                    //		}//inchid verificarea datelor pentru acelasi appid din a doua tabela
                    //	}//inchid for-ul care parcurge restul datelor din cea de-a doua tabela, pornind de la pozitia lui i
					WriteCustomEndElement(objWriter);//inchid DiagnosticS
                    #endregion

                    #region initialConsultDiagnostics
                    objWriter.WriteStartElement("initialConsultDiagnostics", null);//incepe tag-ul initialConsultDiagnostics
                    if (appidgc2 != ds_SIUI_REC_AMB.Tables[1].Rows[i]["AppID"].ToString())
                    {//verific daca appidgc difera de valoarea curenta

                        objWriter.WriteStartElement("diagnostic", null);
                        WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_AMB.Tables[1].Rows[i]["AppID"].ToString());
                        WriteAttributeString(objWriter, "name", ds_SIUI_REC_AMB.Tables[1].Rows[i]["name3"].ToString());
                        //if (ds.Tables[1].Rows[j]["name2"].ToString() != "")
                        //WriteAttributeString(objWriter, "name", ds.Tables[1].Rows[j]["name3"].ToString());
                        //appidgc2=ds.Tables[1].Rows[j]["AppID_gc2"].ToString();//appidgc ia valoarea curenta

						WriteCustomEndElement(objWriter);//inchid diagnostic
                        objWriter.Flush(); //poate merge mai repede asa

                    }//inchid verificarea daca appidgc difera de valoarea curenta
                    objWriter.Flush(); //poate merge mai repede asa
                    //		}//inchid verificarea datelor pentru acelasi appid din a doua tabela
                    //	}//inchid for-ul care parcurge restul datelor din cea de-a doua tabela, pornind de la pozitia lui i
					WriteCustomEndElement(objWriter);//inchid initialConsultDiagnostics
                    #endregion

                }//inchid verificarea vechiului appid cu cel nou
            }//inchid primul for
			WriteCustomEndElement(objWriter);//end recoveryAmbService

			WriteCustomEndElement(objWriter);//end recoveryAmbServices
            objWriter.Flush(); //poate merge mai repede asa
        }//inchid verificarea daca am informatii in cea de-a doua tabela returnata din baza de date	
        #endregion

        #region Prescriptions
        string appid1_ = "";
        string appid_ = "";
        string[] visitedAppid_;
        visitedAppid_ = new string[ds_SIUI_REC_AMB.Tables[2].Rows.Count];
        int count_ = -1;
        int isVisited_ = -1;

        //verific daca am date in cea de-a treia tabela din BD	
        if (ds_SIUI_REC_AMB.Tables.Count > 2 && ds_SIUI_REC_AMB.Tables[2].Rows.Count > 0)
        {
            objWriter.WriteStartElement("prescriptions", null);  //incepe elementul parinte Prescriptions
            for (int i = 0; i < ds_SIUI_REC_AMB.Tables[2].Rows.Count; i++)
            {
                //verific daca APPID-ul a mai fost vizitat, daca nu il introduc in vectorul cu noduri vizitate
                isVisited_ = 0;
                for (int l = 0; l <= count_; l++)
                    if (visitedAppid_[l] == ds_SIUI_REC_AMB.Tables[2].Rows[i]["AppId"].ToString())
                        isVisited_ = 1;
                if (isVisited_ == 0)
                {
                    count_++;
                    visitedAppid_[count_] = ds_SIUI_REC_AMB.Tables[2].Rows[i]["AppId"].ToString();
                }

                #region Prescription
                //end verificare daca Appid-ul a mai fost vizitat
                if (appid1_ != ds_SIUI_REC_AMB.Tables[2].Rows[i]["Appid"].ToString() && isVisited_ == 0)
                {//verific vechiul appid cu cel nou

                    objWriter.WriteStartElement("Prescription", null);//incepe elementul Prescription
                    WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_AMB.Tables[2].Rows[i]["AppID"].ToString());
                    WriteAttributeString(objWriter, "stencilNo", ds_SIUI_REC_AMB.Tables[2].Rows[i]["stencilNo"].ToString());
                    WriteAttributeString(objWriter, "personPID", ds_SIUI_REC_AMB.Tables[2].Rows[i]["personPID"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[2].Rows[i]["petientInsuranceHouse"].ToString() != "")
                        WriteAttributeString(objWriter, "petientInsuranceHouse",
                            ds_SIUI_REC_AMB.Tables[2].Rows[i]["petientInsuranceHouse"].ToString());
                    WriteAttributeString(objWriter, "serialNo", ds_SIUI_REC_AMB.Tables[2].Rows[i]["serialNo"].ToString());
                    WriteAttributeString(objWriter, "serialCode", ds_SIUI_REC_AMB.Tables[2].Rows[i]["serialCode"].ToString());
                    WriteAttributeString(objWriter, "contractNo", ds_SIUI_REC_AMB.Tables[2].Rows[i]["contractNo"].ToString());
                    WriteAttributeString(objWriter, "prescriptionDate",
                        Convert.ToDateTime(ds_SIUI_REC_AMB.Tables[2].Rows[i]["prescriptionDate"]).ToString("yyyy-MM-dd"));
                    if (ds_SIUI_REC_AMB.Tables[2].Rows[i]["merNo"].ToString() != "")
                        WriteAttributeString(objWriter, "merNo", ds_SIUI_REC_AMB.Tables[2].Rows[i]["merNo"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[2].Rows[i]["merDate"].ToString() != "")
                        WriteAttributeString(objWriter, "merDate",
                            Convert.ToDateTime(ds_SIUI_REC_AMB.Tables[2].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "patientType", ds_SIUI_REC_AMB.Tables[2].Rows[i]["patientType"].ToString());
                    WriteAttributeString(objWriter, "no", ds_SIUI_REC_AMB.Tables[2].Rows[i]["no"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[2].Rows[i]["nhp"].ToString() != "")
                        WriteAttributeString(objWriter, "nhp", ds_SIUI_REC_AMB.Tables[2].Rows[i]["nhp"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[2].Rows[i]["prescriptionType"].ToString() != "")
                        WriteAttributeString(objWriter, "prescriptionType",
                            ds_SIUI_REC_AMB.Tables[2].Rows[i]["prescriptionType"].ToString());
                    appid1_ = ds_SIUI_REC_AMB.Tables[2].Rows[i]["AppId"].ToString();//appid-ul ia valoarea curenta


                    #region PrescriptionDrug
                    for (int j = i; j < ds_SIUI_REC_AMB.Tables[2].Rows.Count; j++)
                    {
                        if (appid1_ == ds_SIUI_REC_AMB.Tables[2].Rows[j]["AppId"].ToString())
                        {
                            if (appid_ != ds_SIUI_REC_AMB.Tables[2].Rows[j]["AppID_ths"].ToString())
                            {//verific daca valoarea variabilei appid difera de valoarea curenta 
                                objWriter.WriteStartElement("prescriptionDrug", null);//incepe tagul prescriptionDrug
                                WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_AMB.Tables[2].Rows[j]["AppID"].ToString());
                                if (ds_SIUI_REC_AMB.Tables[2].Rows[j]["no"].ToString() != "")
                                    WriteAttributeString(objWriter, "no", ds_SIUI_REC_AMB.Tables[2].Rows[j]["no"].ToString());
                                if (ds_SIUI_REC_AMB.Tables[2].Rows[j]["drugCode"].ToString() != "")
                                    WriteAttributeString(objWriter, "drugCode", ds_SIUI_REC_AMB.Tables[2].Rows[j]["drugCode"].ToString());
                                if (ds_SIUI_REC_AMB.Tables[2].Rows[j]["activeSubstance"].ToString() != "")
                                    WriteAttributeString(objWriter, "activeSubstance",
                                        ds_SIUI_REC_AMB.Tables[2].Rows[j]["activeSubstance"].ToString());
                                if (ds_SIUI_REC_AMB.Tables[2].Rows[j]["concentration"].ToString() != "")
                                    WriteAttributeString(objWriter, "concentration",
                                        ds_SIUI_REC_AMB.Tables[2].Rows[j]["concentration"].ToString());
                                if (ds_SIUI_REC_AMB.Tables[2].Rows[j]["diseaseCategory"].ToString() != "")
                                    WriteAttributeString(objWriter, "diseaseCategory",
                                        ds_SIUI_REC_AMB.Tables[2].Rows[j]["diseaseCategory"].ToString());
                                if (ds_SIUI_REC_AMB.Tables[2].Rows[j]["diseaseCode"].ToString() != "")
                                    WriteAttributeString(objWriter, "diseaseCode",
                                        ds_SIUI_REC_AMB.Tables[2].Rows[j]["diseaseCode"].ToString());
                                if (ds_SIUI_REC_AMB.Tables[2].Rows[j]["pharmaceuticalForm"].ToString() != "")
                                    WriteAttributeString(objWriter, "pharmaceuticalForm",
                                        ds_SIUI_REC_AMB.Tables[2].Rows[j]["pharmaceuticalForm"].ToString());
                                if (ds_SIUI_REC_AMB.Tables[2].Rows[j]["quantity"].ToString() != "")
                                    WriteAttributeString(objWriter, "quantity", ds_SIUI_REC_AMB.Tables[2].Rows[j]["quantity"].ToString());
                                if (ds_SIUI_REC_AMB.Tables[2].Rows[j]["dose"].ToString() != "")
                                    WriteAttributeString(objWriter, "dose", ds_SIUI_REC_AMB.Tables[2].Rows[j]["dose"].ToString());
                                if (ds_SIUI_REC_AMB.Tables[2].Rows[j]["diagnosticType"].ToString() != "")
                                    WriteAttributeString(objWriter, "diagnosticType",
                                        ds_SIUI_REC_AMB.Tables[2].Rows[j]["diagnosticType"].ToString());
                                if (ds_SIUI_REC_AMB.Tables[2].Rows[j]["copmtListTypeCode"].ToString() != "")
                                    WriteAttributeString(objWriter, "copmtListTypeCode",
                                        ds_SIUI_REC_AMB.Tables[2].Rows[j]["copmtListTypeCode"].ToString());
                                if (ds_SIUI_REC_AMB.Tables[2].Rows[j]["copmtListTypePrc"].ToString() != "")
                                    WriteAttributeString(objWriter, "copmtListTypePrc",
                                        ds_SIUI_REC_AMB.Tables[2].Rows[j]["copmtListTypePrc"].ToString());

                                appid_ = ds_SIUI_REC_AMB.Tables[2].Rows[j]["AppID_ths"].ToString();//appid ia valoarea curenta

								WriteCustomEndElement(objWriter);//inchid prescriptionDrug
                                objWriter.Flush(); //poate merge mai repede asa
                            }//inchid verificarea daca appid este diferita de valoarea curenta
                            objWriter.Flush(); //poate merge mai repede asa
                        }//inchid verificarea datelor pentru acelasi appid din a doua tabela
                    }//inchid for-ul care merge incepand de la pozitia i prin toata tabela a doua a rezultatului

                    #endregion  //prescriptionDrug

                    #region PrescriptionTest
                    objWriter.WriteStartElement("prescriptionTest", null);//incepe elementul PrescriptionTest
                    WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_AMB.Tables[2].Rows[i]["AppID"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[2].Rows[i]["testName"].ToString() != "")
                        WriteAttributeString(objWriter, "testName", ds_SIUI_REC_AMB.Tables[2].Rows[i]["testName"].ToString());
                    WriteAttributeString(objWriter, "monthsNo", ds_SIUI_REC_AMB.Tables[2].Rows[i]["monthsNo"].ToString());
                    WriteAttributeString(objWriter, "patientType", ds_SIUI_REC_AMB.Tables[2].Rows[i]["patientType"].ToString());
					WriteCustomEndElement(objWriter);//inchid prescriptionTest
                    #endregion   //prescriptionTest

					WriteCustomEndElement(objWriter);//end Prescription

                }//inchid verificarea vechiului appid cu cel nou
                #endregion   //prescription
            }//inchid primul for

            objWriter.Flush(); //poate merge mai repede asa
			WriteCustomEndElement(objWriter);//end Prescriptions
        }//inchid verificarea daca am informatii in cea de-a treia tabela returnata din baza de date	

        #endregion   //prescriptions

        #region MedicalNotes
        string appid1__ = "";
        string[] visitedAppid__;
        visitedAppid__ = new string[ds_SIUI_REC_AMB.Tables[3].Rows.Count];
        int count__ = -1;
        int isVisited__ = -1;

        //verific daca am date in cea de-a patra tabela din BD
        if (ds_SIUI_REC_AMB.Tables.Count > 3 && ds_SIUI_REC_AMB.Tables[3].Rows.Count > 0)
        {
            objWriter.WriteStartElement("medicalNotes", null);  //incepe elementul parinte MedicalNotes
            for (int i = 0; i < ds_SIUI_REC_AMB.Tables[3].Rows.Count; i++)
            {
                //verific daca APPID-ul a mai fost vizitat, daca nu il introduc in vectorul cu noduri vizitate
                isVisited__ = 0;
                for (int l = 0; l <= count__; l++)
                    if (visitedAppid__[l] == ds_SIUI_REC_AMB.Tables[3].Rows[i]["AppId"].ToString())
                        isVisited__ = 1;
                if (isVisited__ == 0)
                {
                    count__++;
                    visitedAppid__[count__] = ds_SIUI_REC_AMB.Tables[3].Rows[i]["AppId"].ToString();
                }

                #region MedicalNote
                //end verificare daca Appid-ul a mai fost vizitat
                if (appid1__ != ds_SIUI_REC_AMB.Tables[3].Rows[i]["Appid"].ToString() && isVisited__ == 0)
                {//verific vechiul appid cu cel nou

                    objWriter.WriteStartElement("medicalNote", null);//incepe elementul MedicalNote
                    WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_AMB.Tables[3].Rows[i]["AppID"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[3].Rows[i]["serialNo"].ToString() != "")
                        WriteAttributeString(objWriter, "serialNo", ds_SIUI_REC_AMB.Tables[3].Rows[i]["serialNo"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[3].Rows[i]["serialCode"].ToString() != "")
                        WriteAttributeString(objWriter, "serialCode", ds_SIUI_REC_AMB.Tables[3].Rows[i]["serialCode"].ToString());
                    if (ds_SIUI_REC_AMB.Tables[3].Rows[i]["issueDate"].ToString() != "")
                        WriteAttributeString(objWriter, "issueDate",
                            Convert.ToDateTime(ds_SIUI_REC_AMB.Tables[3].Rows[i]["issueDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "personType", ds_SIUI_REC_AMB.Tables[3].Rows[i]["personType"].ToString());
                    WriteAttributeString(objWriter, "personIdentifier", ds_SIUI_REC_AMB.Tables[3].Rows[i]["personIdentifier"].ToString());
                    WriteAttributeString(objWriter, "stencilNo", ds_SIUI_REC_AMB.Tables[3].Rows[i]["stencilNo"].ToString());
                    appid1__ = ds_SIUI_REC_AMB.Tables[3].Rows[i]["AppId"].ToString();//appid-ul ia valoarea curenta

					WriteCustomEndElement(objWriter);//end medicalNote
                }//inchid verificarea vechiului appid cu cel nou
                #endregion   //medicalNote
            }//inchid primul for
            objWriter.Flush(); //poate merge mai repede asa
			WriteCustomEndElement(objWriter);//end medicalNotes
        }//inchid verificarea daca am informatii in cea de-a patra tabela returnata din baza de date

        #endregion //medicalNotes

        #endregion  //report

		WriteCustomEndElement(objWriter);
    }

	private void DoExportSIUI_13(DataSet ds_SIUI_REC_PREV, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;
        string[] arrHDDate = new string[100];

        #region report
        
        objWriter.WriteStartElement("report");//incepe tag-ul report
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(parameters.startDate).ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(parameters.endDate).ToString("yyyy-MM-dd"));

        if (ds_SIUI_REC_PREV.Tables.Count > 0 && ds_SIUI_REC_PREV.Tables[0].Rows.Count > 0)
        {//verific daca am date in prima tabela intoarsa din baza de date
            //if (ds.Tables[0].Rows[0]["AppKey"].ToString() != "") 
            //WriteAttributeString(objWriter, "AppKey",ds.Tables[0].Rows[0]["AppKey"].ToString());
            WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_PREV.Tables[0].Rows[0]["AppId"].ToString());
            WriteAttributeString(objWriter, "medicalUnit", ds_SIUI_REC_PREV.Tables[0].Rows[0]["medicalUnit"].ToString());
            WriteAttributeString(objWriter, "fiscalCode", ds_SIUI_REC_PREV.Tables[0].Rows[0]["fiscalCode"].ToString());
            WriteAttributeString(objWriter, "contractNo", ds_SIUI_REC_PREV.Tables[0].Rows[0]["contractNo"].ToString());
            WriteAttributeString(objWriter, "insuranceHouse", ds_SIUI_REC_PREV.Tables[0].Rows[0]["insuranceHouse"].ToString());
            if (ds_SIUI_REC_PREV.Tables[0].Rows[0]["invoiceNo"].ToString() != "")
                WriteAttributeString(objWriter, "invoiceNo", ds_SIUI_REC_PREV.Tables[0].Rows[0]["invoiceNo"].ToString());
            if (ds_SIUI_REC_PREV.Tables[0].Rows[0]["invoiceDate"].ToString() != "")
                WriteAttributeString(objWriter, "invoiceDate", ds_SIUI_REC_PREV.Tables[0].Rows[0]["invoiceDate"].ToString());
            if (ds_SIUI_REC_PREV.Tables[0].Rows[0]["invoiceValue"].ToString() != "")
                WriteAttributeString(objWriter, "invoiceValue", ds_SIUI_REC_PREV.Tables[0].Rows[0]["invoiceValue"].ToString());
        }//end verificare daca sunt date in prima tabela returnata din baza de date

        #region recoveryPrevServices
        string appid1 = "";
        string appidgc = "";
        string[] visitedAppid;
        int count = -1;
        int isVisited = -1;

        //verificare daca am date in a doua tabela returnata din BD
        if (ds_SIUI_REC_PREV.Tables.Count > 1 && ds_SIUI_REC_PREV.Tables[1].Rows.Count > 0)
        {
			visitedAppid = new string[ds_SIUI_REC_PREV.Tables[1].Rows.Count];
			objWriter.WriteStartElement("recoveryPrevServices", null);	//incepe tag-ul recoveryPrevServices
            for (int i = 0; i < ds_SIUI_REC_PREV.Tables[1].Rows.Count; i++) //primul for
            {
                //verific daca APPID-ul a mai fost vizitat, daca nu il introduc in vectorul cu noduri vizitate
                isVisited = 0;
                for (int l = 0; l <= count; l++)
                    if (visitedAppid[l] == ds_SIUI_REC_PREV.Tables[1].Rows[i]["AppId"].ToString())
                        isVisited = 1;
                if (isVisited == 0)
                {
                    count++;
                    visitedAppid[count] = ds_SIUI_REC_PREV.Tables[1].Rows[i]["AppId"].ToString();
                }
                #region recoveryPrevService
                //end verificare daca Appid-ul a mai fost vizitat
                if (appid1 != ds_SIUI_REC_PREV.Tables[1].Rows[i]["Appid"].ToString() && isVisited == 0)
                {//verific vechiul appid cu cel nou
                    if (appid1 != "")
                    {
                        //inseamna ca variabila appId a fost modificata cu o alta valoare, trebuie inchis tag-ul 
                        //recoveryPrevService pentru appid-ul vechi
						WriteCustomEndElement(objWriter);//recoveryPrevService

                    }//inchid tag-ul recoveryPrevService pentru valoarea precedenta a AppId-ului
                    objWriter.WriteStartElement("recoveryPrevService", null); //incepe tag-ul recoveryPrevService din nou!!!
                    WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_PREV.Tables[1].Rows[i]["AppID"].ToString());
                    WriteAttributeString(objWriter, "personType", ds_SIUI_REC_PREV.Tables[1].Rows[i]["personType"].ToString());
                    WriteAttributeString(objWriter, "personIdentifier",
                        ds_SIUI_REC_PREV.Tables[1].Rows[i]["personIdentifier"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["personFirstName"].ToString() != "")
                        WriteAttributeString(objWriter, "personFirstName", ds_SIUI_REC_PREV.Tables[1].Rows[i]["personFirstName"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["personLastName"].ToString() != "")
                        WriteAttributeString(objWriter, "personLastName", ds_SIUI_REC_PREV.Tables[1].Rows[i]["personLastName"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["country"].ToString() != "")
                        WriteAttributeString(objWriter, "country", ds_SIUI_REC_PREV.Tables[1].Rows[i]["country"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["birthDate"].ToString() != "")
                        WriteAttributeString(objWriter, "birthDate",
                            Convert.ToDateTime(ds_SIUI_REC_PREV.Tables[1].Rows[i]["birthDate"]).ToString("yyyy-MM-dd"));
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["emissiveOrgUnitName"].ToString() != "")
                        WriteAttributeString(objWriter, "emissiveOrgUnitName",
                            ds_SIUI_REC_PREV.Tables[1].Rows[i]["emissiveOrgUnitName"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["emissiveOrgUnitAddress"].ToString() != "")
                        WriteAttributeString(objWriter, "emissiveOrgUnitAddress",
                            ds_SIUI_REC_PREV.Tables[1].Rows[i]["emissiveOrgUnitAddress"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["emissiveOrgUnitUIC"].ToString() != "")
                        WriteAttributeString(objWriter, "emissiveOrgUnitUIC",
                            ds_SIUI_REC_PREV.Tables[1].Rows[i]["emissiveOrgUnitUIC"].ToString());
                    WriteAttributeString(objWriter, "hospitalizationDaysNo",
                        ds_SIUI_REC_PREV.Tables[1].Rows[i]["hospitalizationDaysNo"].ToString());
                    WriteAttributeString(objWriter, "hospitalizationEnterDate",
                        Convert.ToDateTime(ds_SIUI_REC_PREV.Tables[1].Rows[i]["hospitalizationEnterDate"]).ToString("yyyy-MM-dd"));
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["hospitalizationExitDate"].ToString() != "")
                        WriteAttributeString(objWriter, "hospitalizationExitDate",
                            Convert.ToDateTime(ds_SIUI_REC_PREV.Tables[1].Rows[i]["hospitalizationExitDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "sectionCode", ds_SIUI_REC_PREV.Tables[1].Rows[i]["sectionCode"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["reportedTariffPerDay"].ToString() != "")
                        WriteAttributeString(objWriter, "reportedTariffPerDay",
                            ds_SIUI_REC_PREV.Tables[1].Rows[i]["reportedTariffPerDay"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["assistanceType"].ToString() != "")
                        WriteAttributeString(objWriter, "assistanceType", ds_SIUI_REC_PREV.Tables[1].Rows[i]["assistanceType"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["stencilNo"].ToString() != "")
                        WriteAttributeString(objWriter, "stencilNo", ds_SIUI_REC_PREV.Tables[1].Rows[i]["stencilNo"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["refferedByNo"].ToString() != "")
                        WriteAttributeString(objWriter, "refferedByNo", ds_SIUI_REC_PREV.Tables[1].Rows[i]["refferedByNo"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["refferedBySerialCode"].ToString() != "")
                        WriteAttributeString(objWriter, "refferedBySerialCode",
                            ds_SIUI_REC_PREV.Tables[1].Rows[i]["refferedBySerialCode"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["refferedByStencilNo"].ToString() != "")
                        WriteAttributeString(objWriter, "refferedByStencilNo",
                            ds_SIUI_REC_PREV.Tables[1].Rows[i]["refferedByStencilNo"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["refferedByDate"].ToString() != "")
                        WriteAttributeString(objWriter, "refferedByDate", ds_SIUI_REC_PREV.Tables[1].Rows[i]["refferedByDate"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["refferedBySpecialty"].ToString() != "")
                        WriteAttributeString(objWriter, "refferedBySpecialty",
                            ds_SIUI_REC_PREV.Tables[1].Rows[i]["refferedBySpecialty"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[1].Rows[i]["refferedByContractNo"].ToString() != "")
                        WriteAttributeString(objWriter, "refferedByContractNo",
                            ds_SIUI_REC_PREV.Tables[1].Rows[i]["refferedByContractNo"].ToString());

                    appid1 = ds_SIUI_REC_PREV.Tables[1].Rows[i]["AppId"].ToString();//appid-ul ia valoarea curenta
                #endregion

                    #region Diagnostics
                    for (int j = i; j < ds_SIUI_REC_PREV.Tables[1].Rows.Count; j++)
                    {
                        if (appid1 == ds_SIUI_REC_PREV.Tables[1].Rows[j]["AppID"].ToString())
                        {
                            if (i == j)
                            {
                                objWriter.WriteStartElement("diagnostics", null);//incepe tag-ul Diagnostics
                            }
                            if (appidgc != ds_SIUI_REC_PREV.Tables[1].Rows[j]["AppID_gc"].ToString())
                            {//verific daca appidgc difera de valoarea curenta

                                objWriter.WriteStartElement("diagnostic", null);
                                WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_PREV.Tables[1].Rows[j]["AppID"].ToString());
                                if (ds_SIUI_REC_PREV.Tables[1].Rows[j]["name"].ToString() != "")
                                    WriteAttributeString(objWriter, "name", ds_SIUI_REC_PREV.Tables[1].Rows[j]["name"].ToString());
                                appidgc = ds_SIUI_REC_PREV.Tables[1].Rows[j]["AppID_gc"].ToString();//appidgc ia valoarea curenta

								WriteCustomEndElement(objWriter);//inchid diagnostic
                                objWriter.Flush(); //poate merge mai repede asa

                            }//inchid verificarea daca appidgc difera de valoarea curenta
                            objWriter.Flush(); //poate merge mai repede asa
                        }//inchid verificarea datelor pentru acelasi appid din a doua tabela
                    }//inchid for-ul care parcurge restul datelor din cea de-a doua tabela, pornind de la pozitia lui i
					WriteCustomEndElement(objWriter);//inchid diagnosticS
                    #endregion

                }//inchid verificarea vechiului appid cu cel nou
            }//inchid primul for
			WriteCustomEndElement(objWriter);//end recoveryPrevService

			WriteCustomEndElement(objWriter);//end recoveryPrevServices
            objWriter.Flush(); //poate merge mai repede asa
        }//inchid verificarea daca am informatii in cea de-a doua tabela returnata din baza de date	

        #endregion

        #region Prescriptions
        string appid1_ = "";
        string appid_ = "";
        string[] visitedAppid_;
        int count_ = -1;
        int isVisited_ = -1;

        //verific daca am date in cea de-a treia tabela din BD	
        if (ds_SIUI_REC_PREV.Tables.Count > 2 && ds_SIUI_REC_PREV.Tables[2].Rows.Count > 0)
        {
			visitedAppid_ = new string[ds_SIUI_REC_PREV.Tables[2].Rows.Count];
			objWriter.WriteStartElement("prescriptions", null);  //incepe elementul parinte Prescriptions
            for (int i = 0; i < ds_SIUI_REC_PREV.Tables[2].Rows.Count; i++)
            {
                //verific daca APPID-ul a mai fost vizitat, daca nu il introduc in vectorul cu noduri vizitate
                isVisited_ = 0;
                for (int l = 0; l <= count_; l++)
                    if (visitedAppid_[l] == ds_SIUI_REC_PREV.Tables[2].Rows[i]["AppId"].ToString())
                        isVisited_ = 1;
                if (isVisited_ == 0)
                {
                    count_++;
                    visitedAppid_[count_] = ds_SIUI_REC_PREV.Tables[2].Rows[i]["AppId"].ToString();
                }

                #region Prescription
                //end verificare daca Appid-ul a mai fost vizitat
                if (appid1_ != ds_SIUI_REC_PREV.Tables[2].Rows[i]["Appid"].ToString() && isVisited_ == 0)
                {//verific vechiul appid cu cel nou

                    objWriter.WriteStartElement("Prescription", null);//incepe elementul Prescription
                    WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_PREV.Tables[2].Rows[i]["AppID"].ToString());
                    WriteAttributeString(objWriter, "stencilNo", ds_SIUI_REC_PREV.Tables[2].Rows[i]["stencilNo"].ToString());
                    WriteAttributeString(objWriter, "personPID", ds_SIUI_REC_PREV.Tables[2].Rows[i]["personPID"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[2].Rows[i]["petientInsuranceHouse"].ToString() != "")
                        WriteAttributeString(objWriter, "petientInsuranceHouse", ds_SIUI_REC_PREV.Tables[2].Rows[i]["petientInsuranceHouse"].ToString());
                    WriteAttributeString(objWriter, "serialNo", ds_SIUI_REC_PREV.Tables[2].Rows[i]["serialNo"].ToString());
                    WriteAttributeString(objWriter, "serialCode", ds_SIUI_REC_PREV.Tables[2].Rows[i]["serialCode"].ToString());
                    WriteAttributeString(objWriter, "contractNo", ds_SIUI_REC_PREV.Tables[2].Rows[i]["contractNo"].ToString());
                    WriteAttributeString(objWriter, "prescriptionDate", Convert.ToDateTime(ds_SIUI_REC_PREV.Tables[2].Rows[i]["prescriptionDate"]).ToString("yyyy-MM-dd"));
                    if (ds_SIUI_REC_PREV.Tables[2].Rows[i]["merNo"].ToString() != "")
                        WriteAttributeString(objWriter, "merNo", ds_SIUI_REC_PREV.Tables[2].Rows[i]["merNo"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[2].Rows[i]["merDate"].ToString() != "")
                        WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(ds_SIUI_REC_PREV.Tables[2].Rows[i]["merDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "patientType", ds_SIUI_REC_PREV.Tables[2].Rows[i]["patientType"].ToString());
                    WriteAttributeString(objWriter, "no", ds_SIUI_REC_PREV.Tables[2].Rows[i]["no"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[2].Rows[i]["nhp"].ToString() != "")
                        WriteAttributeString(objWriter, "nhp", ds_SIUI_REC_PREV.Tables[2].Rows[i]["nhp"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[2].Rows[i]["prescriptionType"].ToString() != "")
                        WriteAttributeString(objWriter, "prescriptionType", ds_SIUI_REC_PREV.Tables[2].Rows[i]["prescriptionType"].ToString());
                    appid1_ = ds_SIUI_REC_PREV.Tables[2].Rows[i]["AppId"].ToString();//appid-ul ia valoarea curenta


                    #region PrescriptionDrug
                    for (int j = i; j < ds_SIUI_REC_PREV.Tables[2].Rows.Count; j++)
                    {
                        if (appid1_ == ds_SIUI_REC_PREV.Tables[2].Rows[j]["AppId"].ToString())
                        {
                            if (appid_ != ds_SIUI_REC_PREV.Tables[2].Rows[j]["AppID_ths"].ToString())
                            {//verific daca valoarea variabilei appid difera de valoarea curenta 
                                objWriter.WriteStartElement("prescriptionDrug", null);//incepe tagul prescriptionDrug
                                WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_PREV.Tables[2].Rows[j]["AppID"].ToString());
                                if (ds_SIUI_REC_PREV.Tables[2].Rows[j]["no"].ToString() != "")
                                    WriteAttributeString(objWriter, "no", ds_SIUI_REC_PREV.Tables[2].Rows[j]["no"].ToString());
                                if (ds_SIUI_REC_PREV.Tables[2].Rows[j]["drugCode"].ToString() != "")
                                    WriteAttributeString(objWriter, "drugCode", ds_SIUI_REC_PREV.Tables[2].Rows[j]["drugCode"].ToString());
                                if (ds_SIUI_REC_PREV.Tables[2].Rows[j]["activeSubstance"].ToString() != "")
                                    WriteAttributeString(objWriter, "activeSubstance", ds_SIUI_REC_PREV.Tables[2].Rows[j]["activeSubstance"].ToString());
                                if (ds_SIUI_REC_PREV.Tables[2].Rows[j]["concentration"].ToString() != "")
                                    WriteAttributeString(objWriter, "concentration", ds_SIUI_REC_PREV.Tables[2].Rows[j]["concentration"].ToString());
                                if (ds_SIUI_REC_PREV.Tables[2].Rows[j]["diseaseCategory"].ToString() != "")
                                    WriteAttributeString(objWriter, "diseaseCategory", ds_SIUI_REC_PREV.Tables[2].Rows[j]["diseaseCategory"].ToString());
                                if (ds_SIUI_REC_PREV.Tables[2].Rows[j]["diseaseCode"].ToString() != "")
                                    WriteAttributeString(objWriter, "diseaseCode", ds_SIUI_REC_PREV.Tables[2].Rows[j]["diseaseCode"].ToString());
                                if (ds_SIUI_REC_PREV.Tables[2].Rows[j]["pharmaceuticalForm"].ToString() != "")
                                    WriteAttributeString(objWriter, "pharmaceuticalForm", ds_SIUI_REC_PREV.Tables[2].Rows[j]["pharmaceuticalForm"].ToString());
                                if (ds_SIUI_REC_PREV.Tables[2].Rows[j]["quantity"].ToString() != "")
                                    WriteAttributeString(objWriter, "quantity", ds_SIUI_REC_PREV.Tables[2].Rows[j]["quantity"].ToString());
                                if (ds_SIUI_REC_PREV.Tables[2].Rows[j]["dose"].ToString() != "")
                                    WriteAttributeString(objWriter, "dose", ds_SIUI_REC_PREV.Tables[2].Rows[j]["dose"].ToString());
                                if (ds_SIUI_REC_PREV.Tables[2].Rows[j]["diagnosticType"].ToString() != "")
                                    WriteAttributeString(objWriter, "diagnosticType", ds_SIUI_REC_PREV.Tables[2].Rows[j]["diagnosticType"].ToString());
                                if (ds_SIUI_REC_PREV.Tables[2].Rows[j]["copmtListTypeCode"].ToString() != "")
                                    WriteAttributeString(objWriter, "copmtListTypeCode", ds_SIUI_REC_PREV.Tables[2].Rows[j]["copmtListTypeCode"].ToString());
                                if (ds_SIUI_REC_PREV.Tables[2].Rows[j]["copmtListTypePrc"].ToString() != "")
                                    WriteAttributeString(objWriter, "copmtListTypePrc", ds_SIUI_REC_PREV.Tables[2].Rows[j]["copmtListTypePrc"].ToString());

                                appid_ = ds_SIUI_REC_PREV.Tables[2].Rows[j]["AppID_ths"].ToString();//appid ia valoarea curenta

								WriteCustomEndElement(objWriter);//inchid prescriptionDrug
                                objWriter.Flush(); //poate merge mai repede asa
                            }//inchid verificarea daca appid este diferita de valoarea curenta
                            objWriter.Flush(); //poate merge mai repede asa
                        }//inchid verificarea datelor pentru acelasi appid din a doua tabela
                    }//inchid for-ul care merge incepand de la pozitia i prin toata tabela a doua a rezultatului

                    #endregion  //prescriptionDrug

                    #region PrescriptionTest
                    objWriter.WriteStartElement("prescriptionTest", null);//incepe elementul PrescriptionTest
                    WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_PREV.Tables[2].Rows[i]["AppID"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[2].Rows[i]["testName"].ToString() != "")
                        WriteAttributeString(objWriter, "testName", ds_SIUI_REC_PREV.Tables[2].Rows[i]["testName"].ToString());
                    WriteAttributeString(objWriter, "monthsNo", ds_SIUI_REC_PREV.Tables[2].Rows[i]["monthsNo"].ToString());
                    WriteAttributeString(objWriter, "patientType", ds_SIUI_REC_PREV.Tables[2].Rows[i]["patientType"].ToString());
					WriteCustomEndElement(objWriter);//inchid prescriptionTest
                    #endregion   //prescriptionTest

					WriteCustomEndElement(objWriter);//end Prescription

                }//inchid verificarea vechiului appid cu cel nou
                #endregion   //prescription
            }//inchid primul for
			WriteCustomEndElement(objWriter);//end Prescriptions
            objWriter.Flush(); //poate merge mai repede asa
        }//inchid verificarea daca am informatii in cea de-a treia tabela returnata din baza de date	

        #endregion   //prescriptions

        #region MedicalNotes
        string appid1__ = "";
        string appid__ = "";
        string[] visitedAppid__;
        int count__ = -1;
        int isVisited__ = -1;

        //verific daca am date in cea de-a patra tabela din BD	
        if (ds_SIUI_REC_PREV.Tables.Count > 3 && ds_SIUI_REC_PREV.Tables[3].Rows.Count > 0)
        {
			visitedAppid__ = new string[ds_SIUI_REC_PREV.Tables[3].Rows.Count];
			objWriter.WriteStartElement("medicalNotes", null);  //incepe elementul parinte medicalNotes
            for (int i = 0; i < ds_SIUI_REC_PREV.Tables[3].Rows.Count; i++)
            {
                //verific daca APPID-ul a mai fost vizitat, daca nu il introduc in vectorul cu noduri vizitate
                isVisited__ = 0;
                for (int l = 0; l <= count__; l++)
                    if (visitedAppid__[l] == ds_SIUI_REC_PREV.Tables[3].Rows[i]["AppId"].ToString())
                        isVisited__ = 1;
                if (isVisited__ == 0)
                {
                    count__++;
                    visitedAppid__[count__] = ds_SIUI_REC_PREV.Tables[3].Rows[i]["AppId"].ToString();
                }

                #region MedicalNote
                //end verificare daca Appid-ul a mai fost vizitat
                if (appid1__ != ds_SIUI_REC_PREV.Tables[3].Rows[i]["Appid"].ToString() && isVisited__ == 0)
                {//verific vechiul appid cu cel nou

                    objWriter.WriteStartElement("medicalNote", null);//incepe elementul medicalNote
                    WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_PREV.Tables[3].Rows[i]["AppID"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[3].Rows[i]["serialNo"].ToString() != "")
                        WriteAttributeString(objWriter, "serialNo", ds_SIUI_REC_PREV.Tables[3].Rows[i]["serialNo"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[3].Rows[i]["serialCode"].ToString() != "")
                        WriteAttributeString(objWriter, "serialCode", ds_SIUI_REC_PREV.Tables[3].Rows[i]["serialCode"].ToString());
                    if (ds_SIUI_REC_PREV.Tables[3].Rows[i]["issueDate"].ToString() != "")
                        WriteAttributeString(objWriter, "issueDate",
                            Convert.ToDateTime(ds_SIUI_REC_PREV.Tables[3].Rows[i]["issueDate"]).ToString("yyyy-MM-dd"));
                    WriteAttributeString(objWriter, "personType", ds_SIUI_REC_PREV.Tables[3].Rows[i]["personType"].ToString());
                    WriteAttributeString(objWriter, "personIdentifier", ds_SIUI_REC_PREV.Tables[3].Rows[i]["personIdentifier"].ToString());
                    WriteAttributeString(objWriter, "stencilNo", ds_SIUI_REC_PREV.Tables[3].Rows[i]["stencilNo"].ToString());
                    appid1__ = ds_SIUI_REC_PREV.Tables[3].Rows[i]["AppId"].ToString();//appid-ul ia valoarea curenta	

                    #region MedicalNoteInvestigation
                    for (int j = i; j < ds_SIUI_REC_PREV.Tables[3].Rows.Count; j++)
                    {
                        if (appid1__ == ds_SIUI_REC_PREV.Tables[3].Rows[j]["AppId"].ToString())
                        {
                            if (appid__ != ds_SIUI_REC_PREV.Tables[3].Rows[j]["AppID_ths"].ToString())
                            {//verific daca valoarea variabilei appid difera de valoarea curenta 
                                //incepe tagul medicalNoteInvestigation
                                objWriter.WriteStartElement("medicalNoteInvestigation", null);
                                WriteAttributeString(objWriter, "AppID", ds_SIUI_REC_PREV.Tables[3].Rows[j]["AppID"].ToString());
                                WriteAttributeString(objWriter, "no", ds_SIUI_REC_PREV.Tables[3].Rows[j]["no"].ToString());
                                WriteAttributeString(objWriter, "investigation",
                                    ds_SIUI_REC_PREV.Tables[3].Rows[j]["investigation"].ToString());
                                WriteAttributeString(objWriter, "quantity", ds_SIUI_REC_PREV.Tables[3].Rows[j]["quantity"].ToString());
                                appid__ = ds_SIUI_REC_PREV.Tables[3].Rows[j]["AppID_ths"].ToString();//appid ia valoarea curenta

								WriteCustomEndElement(objWriter);//inchid medicalNoteInvestigation
                                objWriter.Flush(); //poate merge mai repede asa
                            }//inchid verificarea daca appid este diferita de valoarea curenta
                            objWriter.Flush(); //poate merge mai repede asa
                        }//inchid verificarea datelor pentru acelasi appid din a patra tabela
                    }//inchid for-ul care merge incepand de la pozitia i prin toata tabela a doua a rezultatului

                    #endregion  //medicalNoteInvestigation

					WriteCustomEndElement(objWriter);//end MedicalNote
                }//inchid verificarea vechiului appid cu cel nou
                #endregion   //medicalnote
            }//inchid primul for
			WriteCustomEndElement(objWriter);//end medicalNotes
            objWriter.Flush(); //poate merge mai repede asa
        }//inchid verificarea daca am informatii in cea de-a patra tabela returnata din baza de date	

        #endregion   //medicalNotes

        #endregion   //report

		WriteCustomEndElement(objWriter);
	}

	#region specific Salarizare
	private void DoExportSIUI_Sanatate_1C(DataSet ds_EXPORT_SANATATE_1C, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		SalarizareExportParameters parameters = p as SalarizareExportParameters;
        DataView dv0 = ds_EXPORT_SANATATE_1C.Tables[0].DefaultView;
        DataView dv1 = ds_EXPORT_SANATATE_1C.Tables[1].DefaultView;

        #region Reports
        
        objWriter.WriteStartElement("report");
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		//WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(startDate).ToString("yyyy-MM-dd"));
        //WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(endDate).ToString("yyyy-MM-dd"));


        if (ds_EXPORT_SANATATE_1C.Tables.Count > 1 && dv1.Count > 0)
        {
            objWriter.WriteStartElement("SANATATE_1C", null);
            for (int i = 0; i < dv1.Count; i++)
            {
                objWriter.WriteStartElement("SANATATE_1C", null);

                WriteAttributeString(objWriter, "LN_1", dv1[i]["LN_1"].ToString());
                WriteAttributeString(objWriter, "AN_1", dv1[i]["AN_1"].ToString());
                WriteAttributeString(objWriter, "CF_1", dv1[i]["CF_1"].ToString());
                WriteAttributeString(objWriter, "RJ_1", dv1[i]["RJ_1"].ToString());
                WriteAttributeString(objWriter, "RN_1", dv1[i]["RN_1"].ToString());
                WriteAttributeString(objWriter, "RA_1", dv1[i]["RA_1"].ToString());
                WriteAttributeString(objWriter, "CAS_ASIG_1", dv1[i]["CAS_ASIG_1"].ToString());
                WriteAttributeString(objWriter, "SDLA_1", dv1[i]["SDLA_1"].ToString());
                WriteAttributeString(objWriter, "SVTA_1", dv1[i]["SVTA_1"].ToString());
                WriteAttributeString(objWriter, "SDL_ASIG_1", dv1[i]["SDL_ASIG_1"].ToString());
                WriteAttributeString(objWriter, "SVT_ASIG_1", dv1[i]["SVT_ASIG_1"].ToString());
                WriteAttributeString(objWriter, "NREP_1", dv1[i]["NREP_1"].ToString());
                WriteAttributeString(objWriter, "PREP_1", dv1[i]["PREP_1"].ToString());

				WriteCustomEndElement(objWriter);
            }

			WriteCustomEndElement(objWriter);
        }

		WriteCustomEndElement(objWriter);
        objWriter.Flush();
        #endregion
    }

	private void DoExportSIUI_Sanatate_2A(DataSet ds_EXPORT_SANATATE_2A, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		SalarizareExportParameters parameters = p as SalarizareExportParameters;
        DataView dv0 = ds_EXPORT_SANATATE_2A.Tables[0].DefaultView;
        DataView dv1 = ds_EXPORT_SANATATE_2A.Tables[1].DefaultView;

        #region Reports
        
        objWriter.WriteStartElement("report");
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		//WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(startDate).ToString("yyyy-MM-dd"));
        //WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(endDate).ToString("yyyy-MM-dd"));


        if (ds_EXPORT_SANATATE_2A.Tables.Count > 1 && dv1.Count > 0)
        {
            objWriter.WriteStartElement("SANATATE_2A", null);
            for (int i = 0; i < dv1.Count; i++)
            {
                objWriter.WriteStartElement("SANATATE_2A", null);

                WriteAttributeString(objWriter, "LN_1", dv1[i]["LN_1"].ToString());
                WriteAttributeString(objWriter, "AN_1", dv1[i]["AN_1"].ToString());
                WriteAttributeString(objWriter, "CF", dv1[i]["CF"].ToString());
                WriteAttributeString(objWriter, "RJ_1", dv1[i]["RJ_1"].ToString());
                WriteAttributeString(objWriter, "RN_1", dv1[i]["RN_1"].ToString());
                WriteAttributeString(objWriter, "RA_1", dv1[i]["RA_1"].ToString());
                WriteAttributeString(objWriter, "CNP_1", dv1[i]["CNP_1"].ToString());
                WriteAttributeString(objWriter, "NUME_1", dv1[i]["NUME_1"].ToString());
                WriteAttributeString(objWriter, "PRENUME_1", dv1[i]["PRENUME_1"].ToString());
                WriteAttributeString(objWriter, "CAT_1", dv1[i]["CAT_1"].ToString());
                WriteAttributeString(objWriter, "ANG_1", dv1[i]["ANG_1"].ToString());
                WriteAttributeString(objWriter, "PL_1", dv1[i]["PL_1"].ToString());
                WriteAttributeString(objWriter, "SDL_1", dv1[i]["SDL_1"].ToString());
                WriteAttributeString(objWriter, "SVL_1", dv1[i]["SVL_1"].ToString());
                WriteAttributeString(objWriter, "NREP_1", dv1[i]["NREP_1"].ToString());
                WriteAttributeString(objWriter, "PREP_1", dv1[i]["PREP_1"].ToString());

				WriteCustomEndElement(objWriter);
            }

			WriteCustomEndElement(objWriter);
        }

		WriteCustomEndElement(objWriter);
        objWriter.Flush();
        #endregion
    }

	private void DoExportSIUI_Sanatate_2B(DataSet ds_EXPORT_SANATATE_2B, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		SalarizareExportParameters parameters = p as SalarizareExportParameters;
        DataView dv0 = ds_EXPORT_SANATATE_2B.Tables[0].DefaultView;
        DataView dv1 = ds_EXPORT_SANATATE_2B.Tables[1].DefaultView;

        #region Reports
        
        objWriter.WriteStartElement("report");
        WriteAttributeString(objWriter, "xmlns", "http://localhost");
        WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		//WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(startDate).ToString("yyyy-MM-dd"));
        //WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(endDate).ToString("yyyy-MM-dd"));


        if (ds_EXPORT_SANATATE_2B.Tables.Count > 1 && dv1.Count > 0)
        {
            objWriter.WriteStartElement("SANATATE_2B", null);
            for (int i = 0; i < dv1.Count; i++)
            {
                objWriter.WriteStartElement("SANATATE_2B", null);

                WriteAttributeString(objWriter, "LN_1", dv1[i]["LN_1"].ToString());
                WriteAttributeString(objWriter, "AN_1", dv1[i]["AN_1"].ToString());
                WriteAttributeString(objWriter, "CF", dv1[i]["CF"].ToString());
                WriteAttributeString(objWriter, "RJ_1", dv1[i]["RJ_1"].ToString());
                WriteAttributeString(objWriter, "RN_1", dv1[i]["RN_1"].ToString());
                WriteAttributeString(objWriter, "RA_1", dv1[i]["RA_1"].ToString());
                WriteAttributeString(objWriter, "CNP_1", dv1[i]["CNP_1"].ToString());
                WriteAttributeString(objWriter, "CNPC_1", dv1[i]["CNPC_1"].ToString());
                WriteAttributeString(objWriter, "numec1_1", dv1[i]["numec1_1"].ToString());
                WriteAttributeString(objWriter, "prenumec1_1", dv1[i]["prenumec1_1"].ToString());
                WriteAttributeString(objWriter, "tipc_1", dv1[i]["tipc_1"].ToString());
                WriteAttributeString(objWriter, "NREP_1", dv1[i]["NREP_1"].ToString());
                WriteAttributeString(objWriter, "PREP_1", dv1[i]["PREP_1"].ToString());

				WriteCustomEndElement(objWriter);
            }

			WriteCustomEndElement(objWriter);
        }

		WriteCustomEndElement(objWriter);
        #endregion
	}
	#endregion

	static string[] tableNames_Primarie = new string[] {
		"Analize", "Departament", "Diagnostice", "Examinari", "Furnizori",
		"IndicatoriEconomici", "Internari", "Medicatie", "Medici", "Norme_Luna",
		"Pacienti", "Paturi", "Personal", "Personal_Departament", "Personal_Luna",
		"Prezentari", "Proceduri", "ProduseFarmaceutice_Iesiri", "ProduseFarmaceutice_Intrari", "Spital",
		"SZ" }; //21 tables
	private void DoExportSIUI_26(DataSet ds_EXPORT_PRIMARIE, ExportParameters p, System.Xml.XmlTextWriter objWriter)
    {
		StandardExportParameters parameters = p as StandardExportParameters;

		if (chkValidation.Checked)
		{
			#region Validation (on a subset of the items!)
			validationXSDFile = parameters.GetXSDValidationFile();
			MemoryStream dummyBuffer = new MemoryStream();
			System.Xml.XmlTextWriter miniWriter = new System.Xml.XmlTextWriter(dummyBuffer, new System.Text.UTF8Encoding(false));
			miniWriter.WriteStartDocument(true);
			miniWriter.WriteStartElement("NewDataSet", null);
			int nTableLimit = ds_EXPORT_PRIMARIE.Tables.Count;
			for (int tableIndex = 1; tableIndex < nTableLimit; ++tableIndex)
			{
				DataView dvi = ds_EXPORT_PRIMARIE.Tables[tableIndex].DefaultView;
				string elementName = dvi.Table.TableName.Replace("vPrim_Spital_", "").Replace("vPrim_", "");
				elementName = tableNames_Primarie[tableIndex - 1];
				int nRowLimit = Math.Min(10, dvi.Count);
				for (int i = 0; i < nRowLimit; i++)
				{
					miniWriter.WriteStartElement(elementName, null);
					foreach (DataColumn c in dvi.Table.Columns)
						if (dvi[i][c.ColumnName] != DBNull.Value)
						{
							miniWriter.WriteStartElement(c.ColumnName, null);
							miniWriter.WriteValue(dvi[i][c.ColumnName]);
							miniWriter.WriteEndElement();
						}
						//TODO: update this when changing the writer below
					miniWriter.WriteEndElement();
				}
			}
			miniWriter.WriteEndElement();//newdataset
			miniWriter.Flush();

			ValidateXMLByXSD(dummyBuffer);
			miniWriter.Close();
			#endregion
		}

        #region Reports
        

        objWriter.WriteStartElement("NewDataSet", null);

        //int nTableLimit = Math.Min(7, ds_EXPORT_PRIMARIE.Tables.Count);
        for (int tableIndex = 1; tableIndex < ds_EXPORT_PRIMARIE.Tables.Count; ++tableIndex)
        {
            DataView dvi = ds_EXPORT_PRIMARIE.Tables[tableIndex].DefaultView;
            string elementName = dvi.Table.TableName.Replace("vPrim_Spital_", "").Replace("vPrim_", "");
            elementName = tableNames_Primarie[tableIndex - 1];
            //if (dvi.Count > 0)
            int nRowLimit = dvi.Count; //nRowLimit = Math.Min(100, dvi.Count);
            for (int i = 0; i < nRowLimit; i++)
            {
                objWriter.WriteStartElement(elementName, null);
                foreach (DataColumn c in dvi.Table.Columns)
                    if (dvi[i][c.ColumnName] != DBNull.Value)
                    {
                        //WriteAttributeString(objWriter, c.ColumnName, dvi[i][c.ColumnName].ToString());
                        objWriter.WriteStartElement(c.ColumnName, null);
                        objWriter.WriteValue(dvi[i][c.ColumnName]);
						WriteCustomEndElement(objWriter);
                    }
					//TODO?: else switch depending on column's type ((and update the mini-writer above too!))
				WriteCustomEndElement(objWriter);
                if (i % 100 == 0)
					objWriter.Flush(); //also does a fs.Flush()
            }
        }
		WriteCustomEndElement(objWriter);

		//WriteCustomEndElement(objWriter); //report
        objWriter.Flush();
        #endregion
	}

	private void DoExportSIUI_Paliativ(DataSet ds_SIUI_Paliativ, ExportParameters p, System.Xml.XmlTextWriter objWriter)
	{
		StandardExportParameters parameters = p as StandardExportParameters;
		int nTables = ds_SIUI_Paliativ.Tables.Count;
		DataTable dt_Paliativ_Metadata = nTables > 0 ? ds_SIUI_Paliativ.Tables[0] : null;
		DataTable dt_Paliativ_Main = nTables > 5 ? ds_SIUI_Paliativ.Tables[5] : null;
		DataTable dt_Paliativ_Prescriptions = nTables > 1 ? ds_SIUI_Paliativ.Tables[1] : null;
		DataTable dt_Paliativ_MedicalNotes = nTables > 2 ? ds_SIUI_Paliativ.Tables[2] : null;
		DataTable dt_Paliativ_ForeignPersons = nTables > 3 ? ds_SIUI_Paliativ.Tables[3] : null;
		DataTable dt_Paliativ_PidLists = nTables > 4 ? ds_SIUI_Paliativ.Tables[4] : null;
		DataTable dt_Paliativ_HomeCare = nTables > 6 ? ds_SIUI_Paliativ.Tables[6] : null;
		DataTable dt_Paliativ_MedicalDevices = nTables > 7 ? ds_SIUI_Paliativ.Tables[7] : null;
		DataTable dt_Paliativ_OtherSuppliers = nTables > 8 ? ds_SIUI_Paliativ.Tables[8] : null;

		#region opening the <report> tag
		objWriter.WriteStartElement("report");
		WriteAttributeString(objWriter, "xmlns", "http://localhost");
		WriteAttributeString(objWriter, "reportingDate", DateTime.Now.ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "startFrom", Convert.ToDateTime(parameters.startDate).ToString("yyyy-MM-dd"));
		WriteAttributeString(objWriter, "endTo", Convert.ToDateTime(parameters.endDate).ToString("yyyy-MM-dd"));

		if (dt_Paliativ_Metadata != null && dt_Paliativ_Metadata.Rows.Count > 0)
		{
			//NB: these are actually REQUIRED attributes... they should be filled with SOMETHING!
			//Optional attributes aren't even mentioned. Those are: AppKey (string), invoiceNo (string[..20]), invoiceDate (date), invoiceValue (decimal).
			DataRow firstMetadataRow = dt_Paliativ_Metadata.Rows[0];
			WriteAttributeString(objWriter, "hospitalCode", firstMetadataRow["fiscalCode"].ToString());
			WriteAttributeString(objWriter, "fiscalCode", firstMetadataRow["fiscalCode"].ToString());
			WriteAttributeString(objWriter, "insuranceHouse", firstMetadataRow["insuranceHouse"].ToString());
			WriteAttributeString(objWriter, "contractNo", firstMetadataRow["contractNo"].ToString());
			WriteAttributeString(objWriter, "AppID", firstMetadataRow["appId"].ToString());
		}
		#endregion

		#region Paliatives

		objWriter.WriteStartElement("Paliatives", null);
		if (dt_Paliativ_Main != null && dt_Paliativ_Main.Rows.Count > 0)
		{
			for (int i = 0; i < dt_Paliativ_Main.Rows.Count; i++)
			{
				DataRow currentMainRow = dt_Paliativ_Main.Rows[i];
				#region Paliativ
				objWriter.WriteStartElement("Paliativ", null);
				WriteAttributeString(objWriter, "AppID", Convert.ToString((i + 1)));
				if (currentMainRow["hospitalDeptCode"].ToString() != "")
					WriteAttributeString(objWriter, "hospitalDeptCode", currentMainRow["hospitalDeptCode"].ToString());
				WriteAttributeString(objWriter, "realisedCasesNo", currentMainRow["realisedCasesNo"].ToString());
				if (currentMainRow["invalidatedCasesNo"].ToString() != "")
					WriteAttributeString(objWriter, "invalidatedCasesNo", currentMainRow["invalidatedCasesNo"].ToString());
				WriteAttributeString(objWriter, "hospitalizationDays", currentMainRow["hospitalizationDays"].ToString());
				WriteAttributeString(objWriter, "personType", currentMainRow["personType"].ToString());
				if (currentMainRow["fromDate"].ToString() != "")
					WriteAttributeString(objWriter, "fromDate", Convert.ToDateTime(currentMainRow["fromDate"]).ToString("yyyy-MM-dd"));
				if (currentMainRow["toDate"].ToString() != "")
					WriteAttributeString(objWriter, "toDate", Convert.ToDateTime(currentMainRow["toDate"]).ToString("yyyy-MM-dd"));

				//end Paliativ 
				WriteCustomEndElement(objWriter);

				#endregion
			}
		}
		//else
		//{
		//    objWriter.WriteStartElement("Paliativ", null);
		//    WriteAttributeString(objWriter, "AppID", "");
		//    WriteAttributeString(objWriter, "personType", "ASIGURAT");
		//    WriteCustomEndElement(objWriter);
		//}

		WriteCustomEndElement(objWriter); //</Paliatives>
		#endregion

		#region PaliativPrescriptions

		string appID = "";
		int prescriptionDrugNumber = 1;
		if (dt_Paliativ_Prescriptions != null && dt_Paliativ_Prescriptions.Rows.Count > 0)
		{
			objWriter.WriteStartElement("PaliativPrescriptions", null);
			for (int i = 0; i < dt_Paliativ_Prescriptions.Rows.Count; i++)
			{
				DataRow currentPrescriptionRow = dt_Paliativ_Prescriptions.Rows[i];
				if (appID != currentPrescriptionRow["appId"].ToString())
				{
					if (appID != "") // not first
					{
						WriteCustomEndElement(objWriter); // close previous tag
						prescriptionDrugNumber = 1;
					}
					#region PaliativPrescription
					objWriter.WriteStartElement("PaliativPrescription", null);

					WriteAttributeString(objWriter, "AppID", currentPrescriptionRow["AppID"].ToString());
					WriteAttributeString(objWriter, "stencilNo", currentPrescriptionRow["stencilNo"].ToString());
					WriteAttributeString(objWriter, "personPID", currentPrescriptionRow["personPID"].ToString());
					if (currentPrescriptionRow["patientInsuranceHouse"].ToString() != "")
						WriteAttributeString(objWriter, "patientInsuranceHouse", currentPrescriptionRow["patientInsuranceHouse"].ToString());
					if (currentPrescriptionRow["serialNo"].ToString() != "")
						WriteAttributeString(objWriter, "serialNo", currentPrescriptionRow["serialNo"].ToString());
					if (currentPrescriptionRow["serialCode"].ToString() != "")
						WriteAttributeString(objWriter, "serialCode", currentPrescriptionRow["serialCode"].ToString());
					WriteAttributeString(objWriter, "contractNo", currentPrescriptionRow["contractNo"].ToString());
					WriteAttributeString(objWriter, "prescriptionDate", Convert.ToDateTime(currentPrescriptionRow["prescriptionDate"]).ToString("yyyy-MM-dd"));
					if (currentPrescriptionRow["merNo"].ToString() != "") //NB: could force it into string[1..20]?
						WriteAttributeString(objWriter, "merNo", currentPrescriptionRow["merNo"].ToString());
					if (currentPrescriptionRow["merDate"].ToString() != "")
						WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(currentPrescriptionRow["merDate"]).ToString("yyyy-MM-dd"));
					WriteAttributeString(objWriter, "patientType", currentPrescriptionRow["patientType"].ToString());
					if (currentPrescriptionRow["no"].ToString() != "")
						WriteAttributeString(objWriter, "no", currentPrescriptionRow["no"].ToString());
					if (currentPrescriptionRow["nhp"].ToString() != "")
						WriteAttributeString(objWriter, "nhp", currentPrescriptionRow["nhp"].ToString());
					WriteAttributeString(objWriter, "prescriptionType", currentPrescriptionRow["prescriptionType"].ToString());
					if (currentPrescriptionRow["noDaysTreatment"].ToString() != "")
						WriteAttributeString(objWriter, "noDaysTreatment", currentPrescriptionRow["noDaysTreatment"].ToString());
					#endregion

					appID = currentPrescriptionRow["appId"].ToString();
				}
				#region PaliativPrescDrug
				objWriter.WriteStartElement("PaliativPrescDrug", null);

				if (currentPrescriptionRow["no"].ToString() != "")
					WriteAttributeString(objWriter, "no", prescriptionDrugNumber.ToString());
				if (currentPrescriptionRow["drugCode"].ToString() != "")
					WriteAttributeString(objWriter, "drugCode", currentPrescriptionRow["drugCode"].ToString());
				WriteAttributeString(objWriter, "activeSubstance", currentPrescriptionRow["activeSubstance"].ToString());
				if (currentPrescriptionRow["concentration"].ToString() != "")
					WriteAttributeString(objWriter, "concentration", currentPrescriptionRow["concentration"].ToString());
				if (currentPrescriptionRow["diseaseCategory"].ToString() != "")
					WriteAttributeString(objWriter, "diseaseCategory", currentPrescriptionRow["diseaseCategory"].ToString());
				if (currentPrescriptionRow["diseaseCode"].ToString() != "")
					WriteAttributeString(objWriter, "diseaseCode", currentPrescriptionRow["diseaseCode"].ToString());
				if (currentPrescriptionRow["pharmaceuticalForm"].ToString() != "")
					WriteAttributeString(objWriter, "pharmaceuticalForm", currentPrescriptionRow["pharmaceuticalForm"].ToString());
				if (currentPrescriptionRow["quantity"].ToString() != "")
					WriteAttributeString(objWriter, "quantity", currentPrescriptionRow["quantity"].ToString());
				if (currentPrescriptionRow["dose"].ToString() != "")
					WriteAttributeString(objWriter, "dose", currentPrescriptionRow["dose"].ToString());
				WriteAttributeString(objWriter, "diagnosticType", currentPrescriptionRow["diagnosticType"].ToString());

				WriteCustomEndElement(objWriter);
				#endregion
				prescriptionDrugNumber++;
			}
			//end last PaliativPrescription
			WriteCustomEndElement(objWriter);
			//end PaliativPrescriptions
			WriteCustomEndElement(objWriter);
		}
		//else
		//{
		//    objWriter.WriteStartElement("PaliativPrescription", null);
		//    objWriter.WriteStartElement("PaliativPrescDrug", null);
		//    WriteCustomEndElement(objWriter);
		//    WriteCustomEndElement(objWriter);
		//}

		#endregion

		#region PaliativHomeCare

		string prevServCode = "";
		int serviceNumber = 1;
		if (dt_Paliativ_HomeCare != null && dt_Paliativ_HomeCare.Rows.Count > 0)
		{
			objWriter.WriteStartElement("PaliativHomeCare", null);
			for (int i = 0; i < dt_Paliativ_HomeCare.Rows.Count; i++)
			{
				DataRow currentHomeCareRow = dt_Paliativ_HomeCare.Rows[i];
				if (prevServCode != currentHomeCareRow["servCode"].ToString())
				{
					if (prevServCode != "") // not first
					{
						WriteCustomEndElement(objWriter); // close previous tag
						serviceNumber = 1;
					}
					#region PaliativHomeCare
					objWriter.WriteStartElement("PaliativHomeCare", null);

					WriteAttributeString(objWriter, "AppID", currentHomeCareRow["AppID"].ToString());
					WriteAttributeString(objWriter, "serialNo", currentHomeCareRow["serialNo"].ToString());
					WriteAttributeString(objWriter, "serialCode", currentHomeCareRow["serialCode"].ToString());
					WriteAttributeString(objWriter, "recomDate", Convert.ToDateTime(currentHomeCareRow["recomDate"]).ToString("yyyy-MM-dd"));
					if (currentHomeCareRow["repPhysician"].ToString() != "")
						WriteAttributeString(objWriter, "repPhysician", currentHomeCareRow["repPhysician"].ToString());
					if (currentHomeCareRow["repDiagnosticCode"].ToString() != "")
						WriteAttributeString(objWriter, "repDiagnosticCode", currentHomeCareRow["repDiagnosticCode"].ToString());
					if (currentHomeCareRow["repPid"].ToString() != "")
						WriteAttributeString(objWriter, "repPid", currentHomeCareRow["repPid"].ToString());
					#endregion

					prevServCode = currentHomeCareRow["servCode"].ToString();
				}
				#region PaliativServices
				objWriter.WriteStartElement("PaliativServices", null);

				WriteAttributeString(objWriter, "servCode", currentHomeCareRow["servCode"].ToString());
				WriteAttributeString(objWriter, "period", currentHomeCareRow["period"].ToString());
				WriteAttributeString(objWriter, "cycle", currentHomeCareRow["cycle"].ToString());
				WriteAttributeString(objWriter, "qtyPerCycle", currentHomeCareRow["qtyPerCycle"].ToString());

				WriteCustomEndElement(objWriter);
				#endregion
				serviceNumber++;
			}
			//end last PaliativHomeCare
			WriteCustomEndElement(objWriter);
		}
		//else
		//{
		//    objWriter.WriteStartElement("PaliativHomeCare", null);
		//    objWriter.WriteStartElement("PaliativServices", null);
		//    WriteCustomEndElement(objWriter);
		//    WriteCustomEndElement(objWriter);
		//}

		#endregion

		#region PaliativMedicalDevices

		if (dt_Paliativ_MedicalDevices != null && dt_Paliativ_MedicalDevices.Rows.Count > 0)
		{
			objWriter.WriteStartElement("PaliativMedicalDevices", null);
			for (int i = 0; i < dt_Paliativ_MedicalDevices.Rows.Count; i++)
			{
				DataRow currentMedicalDeviceRow = dt_Paliativ_MedicalDevices.Rows[i];
				#region PaliativMedicalDevice
				objWriter.WriteStartElement("PaliativMedicalDevice", null);

				WriteAttributeString(objWriter, "AppID", currentMedicalDeviceRow["AppID"].ToString());
				WriteAttributeString(objWriter, "serialNo", currentMedicalDeviceRow["serialNo"].ToString());
				WriteAttributeString(objWriter, "serialCode", currentMedicalDeviceRow["serialCode"].ToString());
				WriteAttributeString(objWriter, "recomDate", Convert.ToDateTime(currentMedicalDeviceRow["recomDate"]).ToString("yyyy-MM-dd"));
				if (currentMedicalDeviceRow["deviceType"].ToString() != "")
					WriteAttributeString(objWriter, "deviceType", currentMedicalDeviceRow["deviceType"].ToString());
				if (currentMedicalDeviceRow["prothesysType"].ToString() != "")
					WriteAttributeString(objWriter, "prothesysType", currentMedicalDeviceRow["prothesysType"].ToString());
				WriteAttributeString(objWriter, "deviceCode", currentMedicalDeviceRow["deviceCode"].ToString());
				if (currentMedicalDeviceRow["repPhysician"].ToString() != "")
					WriteAttributeString(objWriter, "repPhysician", currentMedicalDeviceRow["repPhysician"].ToString());
				if (currentMedicalDeviceRow["repDiagnosticCode"].ToString() != "")
					WriteAttributeString(objWriter, "repDiagnosticCode", currentMedicalDeviceRow["repDiagnosticCode"].ToString());
				if (currentMedicalDeviceRow["repPid"].ToString() != "")
					WriteAttributeString(objWriter, "repPid", currentMedicalDeviceRow["repPid"].ToString());

				//end PaliativMedicalDevice
				WriteCustomEndElement(objWriter);
				#endregion
			}
			WriteCustomEndElement(objWriter); //</PaliativMedicalDevices>
		}

		#endregion

		#region PaliativMedicalNotes

		if (dt_Paliativ_MedicalNotes != null && dt_Paliativ_MedicalNotes.Rows.Count > 0)
		{
			objWriter.WriteStartElement("PaliativMedicalNotes", null);
			for (int i = 0; i < dt_Paliativ_MedicalNotes.Rows.Count; i++)
			{
				DataRow currentMedicalNoteRow = dt_Paliativ_MedicalNotes.Rows[i];
				#region PaliativMedicalNote
				objWriter.WriteStartElement("PaliativMedicalNote", null);
				WriteAttributeString(objWriter, "AppID", currentMedicalNoteRow["appId"].ToString());
				WriteAttributeString(objWriter, "stencilNo", currentMedicalNoteRow["stencilNo"].ToString());
				WriteAttributeString(objWriter, "personPID", currentMedicalNoteRow["personPID"].ToString());
				if (currentMedicalNoteRow["patientInsuranceHouse"].ToString() != "")
					WriteAttributeString(objWriter, "patientInsuranceHouse", currentMedicalNoteRow["patientInsuranceHouse"].ToString());
				if (currentMedicalNoteRow["serialNo"].ToString() != "")
					WriteAttributeString(objWriter, "serialNo", currentMedicalNoteRow["serialNo"].ToString());
				if (currentMedicalNoteRow["serialCode"].ToString() != "")
					WriteAttributeString(objWriter, "serialCode", currentMedicalNoteRow["serialCode"].ToString());
				WriteAttributeString(objWriter, "issueDate", Convert.ToDateTime(currentMedicalNoteRow["issueDate"]).ToString("yyyy-MM-dd"));
				if (currentMedicalNoteRow["merNo"].ToString() != "")
					WriteAttributeString(objWriter, "merNo", currentMedicalNoteRow["merNo"].ToString());
				if (currentMedicalNoteRow["merDate"] != DBNull.Value)
					WriteAttributeString(objWriter, "merDate", Convert.ToDateTime(currentMedicalNoteRow["merDate"]).ToString("yyyy-MM-dd"));
				WriteAttributeString(objWriter, "ticketType", currentMedicalNoteRow["ticketType"].ToString());
				WriteAttributeString(objWriter, "no", currentMedicalNoteRow["appId"].ToString());
				if (currentMedicalNoteRow["diagnostic"].ToString() != "")
					WriteAttributeString(objWriter, "diagnostic", currentMedicalNoteRow["diagnostic"].ToString());
				if (currentMedicalNoteRow["specialty"].ToString() != "")
					WriteAttributeString(objWriter, "specialty", currentMedicalNoteRow["specialty"].ToString());

				//end PaliativMedicalNote
				WriteCustomEndElement(objWriter);
				#endregion
			}
			//end PaliativMedicalNotes
			WriteCustomEndElement(objWriter);
		}
		//else
		//{
		//    objWriter.WriteStartElement("PaliativMedicalNotes", null);
		//    WriteCustomEndElement(objWriter);
		//}

		#endregion

		#region ForeignPersons

		string prevPersonIdentifier = "";
		int procedureNumber = 1;
		if (dt_Paliativ_ForeignPersons != null && dt_Paliativ_ForeignPersons.Rows.Count > 0)
		{
			objWriter.WriteStartElement("ForeignPersons", null);
			for (int i = 0; i < dt_Paliativ_ForeignPersons.Rows.Count; i++)
			{
				DataRow currentForeignPersonRow = dt_Paliativ_ForeignPersons.Rows[i];
				if (prevPersonIdentifier != currentForeignPersonRow["personIdentifier"].ToString())
				{
					if (prevPersonIdentifier != "") //not first
					{
						WriteCustomEndElement(objWriter); //close previous tag
						procedureNumber = 1;
					}

					#region opening ForeignPerson tag
					objWriter.WriteStartElement("ForeignPerson", null);

					WriteAttributeString(objWriter, "personIdentifier", currentForeignPersonRow["personIdentifier"].ToString());
					if (currentForeignPersonRow["personFirstName"].ToString() != "")
						WriteAttributeString(objWriter, "personFirstName", currentForeignPersonRow["personFirstName"].ToString());
					if (currentForeignPersonRow["personLastName"].ToString() != "")
						WriteAttributeString(objWriter, "personLastName", currentForeignPersonRow["personLastName"].ToString());
					if (currentForeignPersonRow["birthDate"] != DBNull.Value)
						WriteAttributeString(objWriter, "birthDate", Convert.ToDateTime(currentForeignPersonRow["birthDate"]).ToString("yyyy-MM-dd"));

					if (currentForeignPersonRow["countryCode"].ToString() != "")
						WriteAttributeString(objWriter, "countryCode", currentForeignPersonRow["countryCode"].ToString());

					if (currentForeignPersonRow["cardCode"].ToString() != "")
						WriteAttributeString(objWriter, "cardCode", currentForeignPersonRow["personIdentifier"].ToString());

					if (currentForeignPersonRow["cardExpireDate"] != DBNull.Value)
						WriteAttributeString(objWriter, "cardExpireDate", Convert.ToDateTime(currentForeignPersonRow["cardExpireDate"]).ToString("yyyy-MM-dd"));

					if (currentForeignPersonRow["emissiveOrgUnitCode"].ToString() != "")
						WriteAttributeString(objWriter, "emissiveOrgUnitCode", currentForeignPersonRow["emissiveOrgUnitCode"].ToString());
					if (currentForeignPersonRow["emissiveOrgUnitName"].ToString() != "")
						WriteAttributeString(objWriter, "emissiveOrgUnitName", currentForeignPersonRow["emissiveOrgUnitName"].ToString());
					if (currentForeignPersonRow["emissiveOrgUnitAddress"].ToString() != "")
						WriteAttributeString(objWriter, "emissiveOrgUnitAddress", currentForeignPersonRow["emissiveOrgUnitAddress"].ToString());

					//NB: could fill or trim to have an exact length of 36
					WriteAttributeString(objWriter, "caseId", currentForeignPersonRow["caseId"].ToString());
					WriteAttributeString(objWriter, "personType", currentForeignPersonRow["personType"].ToString());
					WriteAttributeString(objWriter, "internmentDate", Convert.ToDateTime(currentForeignPersonRow["internmentDate"]).ToString("yyyy-MM-dd"));
					WriteAttributeString(objWriter, "releaseDate", Convert.ToDateTime(currentForeignPersonRow["releaseDate"]).ToString("yyyy-MM-dd"));
					WriteAttributeString(objWriter, "hospitalDeptCode", currentForeignPersonRow["hospitalDeptCode"].ToString());

					if (currentForeignPersonRow["medicalSheetNo"].ToString() != "") //NB: could trim to length 10
						WriteAttributeString(objWriter, "medicalSheetNo", currentForeignPersonRow["medicalSheetNo"].ToString());
					#endregion
					prevPersonIdentifier = currentForeignPersonRow["personIdentifier"].ToString();
				}
				#region ForeignProcedure
				objWriter.WriteStartElement("ForeignProcedure", null);

				WriteAttributeString(objWriter, "procedureCode", currentForeignPersonRow["procedureCode"].ToString());

				WriteCustomEndElement(objWriter);
				#endregion

				++procedureNumber;

			}
			//end ForeignPerson
			WriteCustomEndElement(objWriter);
			//end ForeignPersons
			WriteCustomEndElement(objWriter);
		}
		//else
		//{
		//    objWriter.WriteStartElement("ForeignPerson", null);
		//    objWriter.WriteStartElement("ForeignProcedure", null);
		//    WriteCustomEndElement(objWriter);
		//    WriteCustomEndElement(objWriter);
		//}

		#endregion

		#region PidLists

		objWriter.WriteStartElement("PidLists", null);
		string prevSheetNo = "";
		int pidListNumber = 1;
		if (dt_Paliativ_PidLists != null && dt_Paliativ_PidLists.Rows.Count > 0)
		{
			for (int i = 0; i < dt_Paliativ_PidLists.Rows.Count; i++)
			{
				DataRow currentPidListRow = dt_Paliativ_PidLists.Rows[i];
				if (prevSheetNo != currentPidListRow["sheetNo"].ToString())
				{
					if (prevSheetNo != "") // not first
					{
						WriteCustomEndElement(objWriter); // close previous
						pidListNumber = 1;
					}
					#region opening PidList tag
					objWriter.WriteStartElement("PidList", null);

					WriteAttributeString(objWriter, "AppID", currentPidListRow["AppID"].ToString());
					WriteAttributeString(objWriter, "pid", currentPidListRow["pid"].ToString()); //NB: Trim(13)

					if (currentPidListRow["specialSituationCode"].ToString() != "") //NB: Trim(20)
						WriteAttributeString(objWriter, "specialSituationCode", currentPidListRow["specialSituationCode"].ToString());
					WriteAttributeString(objWriter, "internmentDate", Convert.ToDateTime(currentPidListRow["internmentDate"]).ToString("yyyy-MM-dd"));
					WriteAttributeString(objWriter, "hospitalDeptCode", currentPidListRow["hospitalDeptCode"].ToString());
					if (currentPidListRow["releaseDate"] != DBNull.Value)
						WriteAttributeString(objWriter, "releaseDate", Convert.ToDateTime(currentPidListRow["releaseDate"]).ToString("yyyy-MM-dd"));
					WriteAttributeString(objWriter, "sheetNo", currentPidListRow["sheetNo"].ToString());
					//required! if (currentPidListRow["case_id"].ToString() != "") //NB: could fill or trim to an exact length of 36
					WriteAttributeString(objWriter, "case_id", currentPidListRow["case_id"].ToString());
					if (currentPidListRow["internmentCriteriaCode"].ToString() != "")
						WriteAttributeString(objWriter, "internmentCriteriaCode", currentPidListRow["internmentCriteriaCode"].ToString());
					WriteAttributeString(objWriter, "birthDate", Convert.ToDateTime(currentPidListRow["birthDate"]).ToString("yyyy-MM-dd"));
					if (currentPidListRow["codeCAS"].ToString() != "")
						WriteAttributeString(objWriter, "codeCAS", currentPidListRow["specialSituationCode"].ToString());
					//optional: transferred (bool).
					#endregion
					prevSheetNo = currentPidListRow["sheetNo"].ToString();
				}
				#region Procedure
				if (currentPidListRow["procedureCode"].ToString() != "")
				{
					objWriter.WriteStartElement("Procedure", null);
					WriteAttributeString(objWriter, "procedureCode", currentPidListRow["procedureCode"].ToString());
					WriteCustomEndElement(objWriter);
				}
				#endregion
				pidListNumber++;
			}
			WriteCustomEndElement(objWriter);
		}
		//else
		//{
		//    objWriter.WriteStartElement("PidList", null);
		//    objWriter.WriteStartElement("Procedure", null);
		//    WriteCustomEndElement(objWriter);
		//    WriteCustomEndElement(objWriter);
		//}

		WriteCustomEndElement(objWriter); // </PidLists>

		#endregion

		#region OtherSuppliers

		objWriter.WriteStartElement("OtherSuppliers", null);
		if (dt_Paliativ_OtherSuppliers != null && dt_Paliativ_OtherSuppliers.Rows.Count > 0)
		{
			for (int i = 0; i < dt_Paliativ_OtherSuppliers.Rows.Count; i++)
			{
				DataRow currentOtherSupplierRow = dt_Paliativ_OtherSuppliers.Rows[i];
				#region OtherSupplier
				objWriter.WriteStartElement("OtherSupplier", null);

				WriteAttributeString(objWriter, "AppID", currentOtherSupplierRow["AppID"].ToString());
				if (currentOtherSupplierRow["personIdentifier"].ToString() != "")
					WriteAttributeString(objWriter, "personIdentifier", currentOtherSupplierRow["personIdentifier"].ToString());
				//NB: could trim to a max length of 20...
				WriteAttributeString(objWriter, "serviceCode", currentOtherSupplierRow["serviceCode"].ToString());
				WriteAttributeString(objWriter, "noServices", currentOtherSupplierRow["noServices"].ToString());
				WriteAttributeString(objWriter, "tariff", currentOtherSupplierRow["tariff"].ToString());
				WriteAttributeString(objWriter, "servicesData", Convert.ToDateTime(currentOtherSupplierRow["servicesData"]).ToString("yyyy-MM-dd"));
				WriteAttributeString(objWriter, "supplierCode", currentOtherSupplierRow["supplierCode"].ToString());
				WriteAttributeString(objWriter, "supplierContractNo", currentOtherSupplierRow["supplierContractNo"].ToString());
				//NB: Restricted to "C"(clinic), "P"(para) or "A"(amb)...
				WriteAttributeString(objWriter, "serviceType", currentOtherSupplierRow["serviceType"].ToString());
				WriteAttributeString(objWriter, "supplierOrgUnit", currentOtherSupplierRow["supplierOrgUnit"].ToString());
				//NB: Trim(10)
				WriteAttributeString(objWriter, "sheetNo", currentOtherSupplierRow["sheetNo"].ToString());

				//end OtherSupplier
				WriteCustomEndElement(objWriter);
				#endregion
			}
		}
		WriteCustomEndElement(objWriter); //</OtherSuppliers>

		#endregion

		//end report
		WriteCustomEndElement(objWriter);
	}
	#endregion

	/// <summary>
	/// Inserts both the END TAG for the current element, and a NewLine character.
	/// </summary>
	/// <param name="writer">The xml writer which will receive the data.</param>
	private static void WriteCustomEndElement(System.Xml.XmlTextWriter writer)
	{
		writer.WriteEndElement();
		writer.WriteWhitespace(System.Environment.NewLine);
	}

    private void ValidateXMLFileByXSD(string sXMLFilePath)
    {
        string filePath = System.Web.HttpContext.Current.Request.MapPath("~/Logs/");
        XMLValidator validator = new XMLValidator(filePath + @"\xml_validation.log");
        validator.Validate(sXMLFilePath, validationXSDFile);
    }

    private void ValidateXMLByXSD(Stream stream)
    {
        string filePath = System.Web.HttpContext.Current.Request.MapPath("~/Logs/");
        XMLValidator validator = new XMLValidator(filePath + @"\xml_validation.log");
		validator.Validate(stream, validationXSDFile); //Careful: this uses a XmlTextReader, which has closeInput == true by default...
    }

    [WebMethod, ScriptMethod]
    public static string getStatus()
    {
        return ""; //statusLog["exp"];
    }

    #region ICallbackEventHandler Members

	public string strMessage
	{
		get { return (string)(this.ViewState["strMessage"] ?? ""); }
		set { this.ViewState["strMessage"] = value; }
	}

	public string GetCallbackResult()
    {
        return strMessage;
    }

    public void RaiseCallbackEvent(String eventArgument)
    {
        strMessage = eventArgument;
    }

    #endregion
}
